Babis.amas
Babis.amas

Reputation: 471

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?

Upvotes: 1

Views: 730

Answers (1)

alexhughesking
alexhughesking

Reputation: 2007

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().

Upvotes: 2

Related Questions