XML Javascript parse problem (specific code question ) - javascript

I'm using the following parser to parse xml
function parseXML(text) {
var doc;
if(window.DOMParser) {
var parser = new DOMParser();
doc = parser.parseFromString(text, "text/xml");
}
else if(window.ActiveXObject) {
doc = new ActiveXObject("Microsoft.XMLDOM");
doc.async = "false";
doc.loadXML(text);
}
else {
throw new Error("Cannot parse XML");
}
return doc;
}
I can't understand why it isn't working on my XML document, obtained via AJAX.
Result via AJAX request:
X-Powered-By PHP/5.2.11
Content-Length 887
Keep-Alive timeout=5, max=95
Connection Keep-Alive
Content-Type text/xml
<?xml version="1.0" encoding="UTF-8"?>
<xml_test>wont work!</xml_test>
Test Code:
var xml = parseXML(data);
$(xml).find("xml_test").each(function()
{
console.info('found xml_test... never happen..');
});
But if I use it like this it works nicely!
var data = '<xml_test>works</xml_test>';
var xml = parseXML(data);
$(xml).find("xml_test").each(function()
{
alert('this works!');
});
I know that this is a specific question but I would appreciate your help and/or suggestions...
Thanks in advance
Pedro

If you use jQuery to request your resource, you should already get XML DOM document in case it was served with text/xml mime-type. Thus no need to parse.

If you're getting your XML via Ajax, there's no need to parse it because the browser will do it for you. Simply use the responseXML property of the XMLHttpRequest object, which will give you an XML document object. jQuery wraps this using "xml" for the dataType:
$.ajax({
type: "GET",
url: "foo.xml",
dataType: "xml",
success: function(xml) {
alert(xml.documentElement.nodeName);
}
});

I use this function and gives me good result:
var myLoadXml = function(s){
var objxml = null;
if(document.implementation && document.implementation.createDocument) {
var objDOMParser = new DOMParser();
objxml = objDOMParser.parseFromString(s, "text/xml");
} else if (window.ActiveXObject) {
objxml = new ActiveXObject('MSXML2.DOMDocument.3.0');
objxml.async = false;
objxml.loadXML(s);
}
return objxml;
};
var xml = myLoadXml(data);
$(xml).find("xml_test").each(function()
{
console.info('found xml_test... never happen..');
});
EDIT
Example
** EDIT II **
function parseXML(text) {
var doc;
if (typeof text == 'object'){ // check type of text
return text;
}
if(window.DOMParser) {
var parser = new DOMParser();
doc = parser.parseFromString(text, "text/xml");
}
else if(window.ActiveXObject) {
doc = new ActiveXObject("Microsoft.XMLDOM");
doc.async = "false";
doc.loadXML(text);
}
else {
throw new Error("Cannot parse XML");
}
return doc;
}

If you are using jQuery (as your test code suggests), you can simply pass the xml to it.
var xml = $(data);

Related

Check if 2 XML documents are identical with javascript

I have 2 xml documents stored which I get from an AJAX post request and I would like to check if they are the same. Obviously xml1 == xml2 is not working. Is there another way that I could make this work?
Try this. It parses the XML document using the method in this question and compares the two using isEqualNode.
function parseXMLString(xmlString) {
var xmlDoc;
if (window.DOMParser) {
var parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlString, "text/xml");
} else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(xmlString);
}
return xmlDoc;
}
var xmlObj1 = parseXMLString('<hello>world</hello>');
var xmlObj2 = parseXMLString('<hello>world</hello>');
var xmlObj3 = parseXMLString('<hello>world2</hello>');
var xmlObj4 = parseXMLString('<hello2>world</hello2>');
console.log(xmlObj1.isEqualNode(xmlObj2));
console.log(xmlObj1.isEqualNode(xmlObj3));
console.log(xmlObj1.isEqualNode(xmlObj4));
If you're using jQuery, you can parse the XML document using parseXML().

Using Javascript to Create a XML Document from a HTML Form

I'm having a lot of difficulty with this project.
My aim is to write the results of a HTML form to an XML Document using Javascript.I have absolutely no idea how to do it.
Reason why I'm coming here is that I want to be sure that I'm on the right track. So far, I'm writing only one line "\n" just to test things out.
Here is my current JavaScript
var xhr = false;
if (window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
function StoreRegXml()
{
xhr.open("GET", "php.php?" + Number(new Date), true);
xhr.onreadystatechange = getData;
xhr.send(null);
}
function getData()
{
if ((xhr.readyState == 4) && (xhr.status == 200))
{
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var filename = "customer.xml";
var file = fso.CreateTextFile(filename, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
file.Close();
}
}
Am I on the right track?
Edit: I'm adding alerts('test1'); to see where the code is going wrong and it stops at
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
Any ideas?
Inside the browser to create and populate an XML DOM document you can use the W3C DOM APIs with e.g.
var xmlDoc = document.implementation.createDocument(null, 'root', null);
var foo = xmlDoc.createElement('foo');
foo.textContent = 'bar';
xmlDoc.documentElement.appendChild(foo);
console.log(xmlDoc);
This creates an in memory XML DOM document, not an XML file. You can then for instance send the xmlDoc with XMLHttpRequest to the server.

No XMLDocument from OpenLayers.Request.Post

I use a asynchronous OpenLayers POST Request and get via responseText this String:
<?xml version="1.0" encoding="UTF-8"?>
<gml:TimePeriod xmlns:gml="http://www.opengis.net/gml">
<gml:beginPosition>2011-10-18T15:15:00.000+02:00</gml:beginPosition>
<gml:endPosition>2014-11-23T14:45:00.000+01:00</gml:endPosition>
</gml:TimePeriod>
For some reason I do not get the response in a XML document object, respectively I got an empty XMLDocument.
My Code so far:
var request = OpenLayers.Request.POST({
url: "http://139.17.3.305:8080/database/sos",
async: true, //is default
data: xmlString,
callback: handler //name of triggered callback function
});
//xml callback handler
function handler(request) {
var xmlText = request.responseText;
console.log(xmlText); //returns the string above
var xmlDoc = request.responseXML;
console.log(xmlDoc); // returns the empty XMLDocument
var timeArray = xmlDoc.getElementsByTagName('TimePeriod');
console.log("timeArray:",timeArray);
};
// create a XML Document
function CreateXMLDocument () {
var xmlDoc = request.responseText;
if (window.DOMParser) {
var parser = new DOMParser();
xmlDoc = parser.parseFromString (xmlDoc, "text/xml");
} else if (window.ActiveXObject) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML (xmlDoc);
}
var TimeNode = xmlDoc.getElementsByTagName ("TimePeriod");
var beginPosition = TimeNode.getAttribute ("beginPosition");
alert ("The Timeperiod is " + beginPosition);
}
Any idea how to get the “TimePeriod” tag into the objekt “timeArray”?
Why does the request work for that string output and not for the XMLDocument?
I've figured it out!
I received my requested time period in an alert by changing a few line of code.
I exchanged the XML alert handler code and left the XML callback handler out.
//xml alert Handler
function handler(request) {
var xmlStr = request.responseText;
console.log("xmlStr:",xmlStr);
var parser=new DOMParser();
var xmlDoc=parser.parseFromString(request.responseText,"text/xml");
var gml = xmlDoc.getElementsByTagName("gml:beginPosition")[0].firstChild.data;
console.log("gml:beginPosition", gml);
alert(gml);
};

load and parse xml from localstorage

I have the following, which loads XML from a web site and parses it:
function load() {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = parse;
xhttp.open('GET', 'http://...XML.xml', false);
xhttp.send();
}
function parse() {
xmlDoc = xhttp.responseXML.documentElement.childNodes;
for (var i = 0; i < xmlDoc.length; i++) {
nodeName = xmlDoc[i].nodeName;
...
}
After I loading this, I store it in localStorage and I can retrieve it as a string. I need to be able to convert it back to a xml document just like:
xmlDoc = xhttp.responseXML.documentElement.childNodes;
does, so i can parse it. I have been looking for awhile now and can not figure it out.
Thanks in advance.
Based on the answer here XML parsing of a variable string in JavaScript Credit to #tim-down
You need to create an XML parser. Then pass the string into your parse instance. Then you should be able to query it as per before.
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
Example usage:
var xml = parseXml("[Your XML string here]");

Cross-Browser Javascript XML Parsing

Are there any cross-browser / cross-platform ways to parse XML files in Javascript?
The following will work in all major browsers, including IE 6:
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
Example usage:
var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);
Live demo:
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
var xml = parseXml("<foo>Stuff</foo>");
document.body.innerHTML = "Root element: " + xml.documentElement.nodeName;
Consider using jQuery.parseXML.
Note that old JQuery's code (pre 2.x) is essentially identical to one proposed in the accepted answer and can be found at http://code.jquery.com/jquery-1.9.1.js, partial version below:
// Cross-browser xml parsing
parseXML: function( data ) {
...
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
...
}
Starting JQuery 2.x code changed to skip ActiveX branch, if you still need it - use older version of JQuery or inline ActiveX parsing. Partial code from http://code.jquery.com/jquery-2.0.0.js:
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
.....
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} catch ( e ) {
xml = undefined;
}
.....
},
If you need to parse large XML documents that you may not be able to completely hold in memory, consider using a SAX style parser like this one: https://github.com/isaacs/sax-js/

Categories

Resources