Check if 2 XML documents are identical with javascript - 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().

Related

Does the browser have an HTML parser that I can access to get errors?

I'm able to parse XML documents in the browser and get error messages using the following code:
// Internet Explorer
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.loadXML(txt);
var hasError = (xmlDoc.parseError.errorCode != 0);
// Firefox, Opera, Webkit
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(text, "text/xml");
var hasError = (xmlDoc.getElementsByTagName("parsererror").length > 0);
But I need to be able to parse an HTML document and check for errors.
Is there an HTML parser I can access in the same way as I'm accessing the XML parser?
UPDATE:
It looks like at least in Firefox I can attempt to create an HTML dom and parse the contents. But it doesn't seem to throw any error or return an error message no matter what I throw at it:
var text = "<html><body><label>test</labe></body></html>";
var parser = new DOMParser();
//var func = function (e) { console.log(e); };
//parser.attachEvent("InvalidStateError", func); // no attachEvent, no addEventListener
var htmlDoc = parser.parseFromString(text, "text/html");
var hasError = (htmlDoc.getElementsByTagName("parsererror").length > 0);
console.log("Has error: " + hasError); // also false. no errors ever.
console.log(htmlDoc);
This page, this page and this page helped me understand the DOMParser class more.

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);
};

Displaying XML data with Javascript

I'm trying to display some XML data in a jsp file.
I'm using EL to get the data below:
<xml id="xmlData">
<c:out value="${xmlform.myXmlData}" escapeXml="false"/>
</xml>
How can I get reference to this xml document using javascript?
var xmlDoc = document.getElementById("xmlData"); //reference to the xml element
var xmlData = xmlDoc.[how to reference xmlDoc to get data?]
var fields = xmlData.documentElement.selectNodes("field");
for (var i=-; i<fields.length;etc...
So the JSP-Server write the XML-tree directly in the HTML-code. I hope this could be helpful for you.
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(document.getElementById("xmlData").innerHTML ,"text/xml");
var fields = xmlDoc.documentElement.getElementsByTagName("field");
for(var i = 0; i < fields.length; i++)
{
console.log(fields[i].firstChild.data); // fields[i].attributes, fields[i]childNodes, ...
}
or shorter:
var xmlData = document.getElementById("xmlData");
var fields = xmlData.getElementsByTagName("field");
for(var i = 0; i < fields.length; i++)
{
console.log(fields[i].firstChild.data);
}
Here is how you can parse XML in javascript.
var xmlDoc;
function parsexml(txt)
{
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml"); //txt is your xml data
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
}
}
function getElementFromXML(tagname)
{
return xmlDoc.getElementsByTagName(tagname)[0].childNodes[0].nodeValue;
}
You have to load your xml file in and then find and manipulate the Nodes as needed.
function loadXMLDoc(filename)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // code for IE5 and IE6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}
All modern browsers have a built-in XML parser.
An XML parser converts an XML document into an XML DOM object - which can then be manipulated with JavaScript.
W3Schools example

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]");

XML Javascript parse problem (specific code question )

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);

Categories

Resources