I have a xml file whose content is
<?xml version="1.0" encoding="UTF-8"?>
<ReturnMessage>
<root>ReturnMessage</root>
<cancelMessage>Request cancelled. /cancelMessage>
<confirmMessage>Click 'Create Document' to continue.</confirmMessage>
</ReturnMessage>
I load my xml like this
var result = responseText;
if (document.implementation && document.implementation.createDocument)
{
alert("firefox");
xml=document.implementation.createDocument("","",null);
xml.load(result);
}
When execute the below code
var cnfmMsgCnt = xml.getElementsByTagName("confirmMessage");
alert(cnfmMsgCnt.lenght);
it alerts a 0 is firefox.
var displayMsg = xml.getElementsByTagName("confirmMessage").item(0).text
also does not provide any output in FF.
It works perfect in IE but it is not working in Firefox.
The method load() takes a file name as argument, not an XML string. See https://developer.mozilla.org/en/DOM/document.load (and more normative: W3C DOM Level 3 Load & Save module)
What you probably want is explained here https://developer.mozilla.org/en/Parsing_and_serializing_XML
var sMyString = "<a id=\"a\"><b id=\"b\">hey!<\/b><\/a>";
var oParser = new DOMParser();
var oDOM = oParser.parseFromString(sMyString, "text/xml");
Related
I am parsing my XML file in HTML and it parses well when I run it in Chrome/Edge browsers, but when I run it in Firefox, it throws this error:
XML Parsing Error: not well-formed
Location: http://127.0.0.1:5500/List.xml
Line Number 21, Column 2:
This is my HTML where I parse it:
<script>
var xml = new XMLHttpRequest();
xml.onreadystatechange = function () {
if (xml.readyState == XMLHttpRequest.DONE) {
var xmlData = xml.responseXML;
if (!xmlData) {
xmlData = (new DOMParser()).parseFromString(xml.responseText, 'text/xml');
var PDF = xmlData.getElementsByTagName("PDF");
var web = PDF[0].getElementsByTagName("link")[0].firstChild.data;
}
}
}
xml.open('GET', 'List.xml', true);
xml.send(null);
</script>
<?xml version = "1.0" ?>
<List>
<PDF>
<id>1</id>
<link>https://www.mywebpage.com/AA.pdf</link>
</PDF>
</List>
</xml>
Your XML is not well-formed. Remove the last </xml> tag.
The <?xml version = "1.0" ?> construct is not a opening element tag that has to be closed. It is an XML declaration.
I am trying to parse XML file using java-script. According to the tutorial I read I found That To get the Root element, I have to use document.documentElement.
I use that syntax but when I tried to display the returned value from that Syntax, the browser displays [object HTMLHtmlElement].
My question is: (1) Why I am getting [object HTMLHtmlElement] displayed in the web browser.
(2) According to the below posted XML-File, What should I expect the output to be
after usingrootElement = document.documentElement;
Please find below the code I used(Javascript) and the XML file.
Javascript
function findWriter()
{
var schriftstellerKnoten, SpracheKnoten;
var FuellerKnoten, DichtungKnoten, Anzeige, rootElement;
rootElement = document.documentElement;
document.write(rootElement);
}
XML file:
<?xml version="1.0" ?>
<Schriftsteller>
<Englischsprache>
<Dichtung>
<fueller>
<name>Jane Austin</name>
<name>Rex Stout</name>
<name>Dashiell Hammett</name>
</fueller>
</Dichtung>
</Englischsprache>
</Schriftsteller>
document.documentElement will get you the root HTML tag of the page in which your javascript is present.
To fetch and display the XML content, you must get access to the XML document and then use it to load the XML file like the following:
function findWriter()
{
var schriftstellerKnoten, SpracheKnoten;
var FuellerKnoten, DichtungKnoten, Anzeige, rootElement;
if (window.XMLHttpRequest){
xhttp=new XMLHttpRequest(); //For non IE browsers
}
else { // for IE 5/6
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET","test.xml",false);
xhttp.send();
xmlDoc=xhttp.responseXML; //Fetch the XML file contents
var nameEl = xmlDoc.documentElement.getElementsByTagName("name"); //Get all <name> tags in it
for (i=0; i<nameEl.length; i++){
document.write("Name" + i + ": " + nameEl[i].firstChild.nodeValue + "<br/>"); //write names
}
}
var xmlDoc;
try {
//For IE
//This is what i am trying to do.But alas! fails.
var xmlDoc ;
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc .async = false;
xmlDoc.loadXML(progressxml);
var xml = xmlDoc;
alert(xml);
} catch(e) { //if exception than For Firefox etc.
try { //Firefox, Mozilla, Opera, etc.
alert("Coming nopt in INE");
parser=new DOMParser();
xmlDoc=parser.parseFromString(progress,"text/xml");
} catch(e) {
alert(e.message)
}
}
var notes = xmlDoc.getElementsByTagName("root")[0];
I am trying to parse a xml string in order to display it on various browsers. Code for Firefox is working good.Problem is with IE section. i.e notes is null. Don't know why??
Sample xml string :
<displayvalue>BANGALORE</displayvalue>
<displayvalue>Rishi prakash barawl</displayvalue>
<displayvalue>3.29</displayvalue>
<displayvalue>a¢ ¶ ® Ë Ý �</displayvalue>
<displayvalue></displayvalue>
<displayvalue>MCA</displayvalue>
breaks on special char tagvalue.
You might need to make sure your XML starts with <?xml version="1.0" encoding="UTF-8" ?> so that the parser that IE uses reads the characters in correctly.
i am trying to upload an xml file using javascript. my javascript code is given below:
var xmlDoc =null;
var abc = new Array();
if (window.ActiveXObject){
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
else if (document.implementation.createDocument){
xmlDoc=document.implementation.createDocument("","",null);
}
else{
alert('Browser cannot handle this script');
}
if (xmlDoc!=null){
xmlDoc.async=false;
xmlDoc.load("employee.xml");
var x = xmlDoc.getElementsByTagName("EMP");
for (i=0;i<x.length;i++)
{
abc[0] = x[0].getElementsByTagName("ID")[0].childNodes[0].nodeValue;
document.write("a is "+abc[0]);
abc[1] = x[0].getElementsByTagName("ID1")[0].childNodes[0].nodeValue;
document.write("<br>b is "+abc[1]);
}
}
and my xml file is:
<EMPLOYEE>
<EMP>
<ID>10.99</ID>
<ID1>20.54</ID1>
</EMP>
</EMPLOYEE>
the code is working properly in IE as well as firefox but in Google Chrome, it is not showing anything. can some one tell me where i am wrong or how to correct it.
In order to get the XML file in Chrome you need to execute a GET. For security reasons you cannot load it in a straight forward manner from the file system. Here's code:
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET", xmlsrc, false);
xmlhttp.send(null);
var xmlDoc = xmlhttp.responseXML.documentElement;
I am sending an xml response from my servlet to my html page. I receive it via the xmlresponse object of the xmlhttprequest object. My xml document contains a xsl:stylesheet as an element I want to extract this element and execute that xslt code in my java script.
Is it possible?
This is my xml code :
<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
Version="2.0" IssueInstant="2012-05-22T13:40:52:390" ProtocolBinding="urn:oasis:na
mes:tc:SAML:2.0:bindings:HTTP-POST" AssertionConsumerServiceURL="localhos
t:8080/consumer.jsp">
<UserID>
xyz
</UserID>
<testing>
text
</testing>
<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
http://localhost:8080/saml/SProvider.jsp
</saml:Issuer>
<xslt>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="text" />
<xsl:template match="/">
UserID : <xsl:copy-of select="//UserID"/>
testing : <xsl:copy-of select="//testing"/>
</xsl:template>
</xsl:stylesheet>
</xslt>
</samlp:AuthnRequest>
Once I get this xml string from the ajax response, I want to convert it into xml, extract the xslt part and execute it and show the output in a text area.
EDIT2
What is wrong with this code :
var xmlDoc=xmlhttp.responseXML;
//var xmltext=new XMLSerializer().serializeToString(xmlDoc);
var xsltProcessor = new XSLTProcessor();
var element=xmlDoc.getElementsByTagNameNS("http://www.w3.org/1999/XSL/Transform","stylesheet");//
//document.forms['my']['signature'].value=xmltext;
var stylesheet=xsltProcessor.importStylesheet(element[0]);
var result=xsltProcessor.transformToDocument(xmlDoc);
var xmltext1=new XMLSerializer().serializeToString(result);
document.forms['my']['signature2'].value = xmltext1;
The output(xmltext1) for the xslt transformation is -
<transformiix:result xmlns:transformiix="http://www.mozilla.org/TransforMiix">
UserID : 1212
Testing : 1212
</transformiix:result>
But if you see in the xslt code, the outputmethod is set to "text". then why are xml tags included in the output?
Answer
This gives the exlpanation for edit2. Thanks for the answers:)
This is what worked for me, though I only tested it in the newest chrome:
var getNsResolver = function (element) {
var ns = {
samlp: 'urn:oasis:names:tc:SAML:2.0:protocol',
xsl: 'http://www.w3.org/1999/XSL/Transform'
};
return function (prefix) {
return ns[prefix] || null;
};
};
var handleResponse = function (xhr) {
var
doc = xhr.responseXML,
xsl = doc.evaluate('/samlp:AuthnRequest/xslt/xsl:stylesheet', doc, getNsResolver(doc.documentElement), XPathResult.ANY_TYPE, null).iterateNext(),
processor = new XSLTProcessor(),
result;
processor.importStylesheet(xsl);
result = processor.transformToFragment(doc, document);
document.getElementById('foo').value = result.textContent;
};
window.addEventListener('load', function () {
var request = new XMLHttpRequest();
request.addEventListener('load', function (evt) {
handleResponse(request);
}, false);
request.open('GET', 'sample.xml', true); // sample.xml contains the xml from the question
request.send();
}, false);
This is what I use to get namespaced xml from an xmlHttpRequest (in your case ns=xsl, not tested):
var xml=xhr.responseXML;
var elts = (xml.getElementsByTagNameNS)?xml.getElementsByTagNameNS("ns","tag"):xml.getElementsByTagName("ns\:tag");
Note that you can only use responseXML if the server returns well formed xml. If not, you'll need to parse xhr.responseText.
I'm using this ATM, works great!
Its a parser written on jQuery
http://www.jongma.org/webtools/jquery/xslt/