1

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?

Babis.amas
  • 469
  • 2
  • 16
  • 4
    There's no built-in way to do that in JavaScript. You'll have to come up with code that performs a comparison between the DOM trees using whatever criteria suit your application. – Pointy Nov 29 '16 at 14:36
  • @Pointy Thank you. That's what I thought but I wanted to make sure that there is not a simpler way. – Babis.amas Nov 29 '16 at 14:41

1 Answers1

1

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

Community
  • 1
  • 1
Alex K
  • 1,937
  • 11
  • 12