Andrey Rubliov
Andrey Rubliov

Reputation: 1595

Xercesc DOMDocument - Compare two XML documents

I am using xercesc (C++) library for processing XML documents with xercesc::XercesDOMParser class. What is the simplest way to compare two XML documents? Say, I use:

XercesDOMParser parser1;
parser1.parse("1.xml");
DOMDocument* doc1 = parser1.getDocument();

XercesDOMParser parser2;
parser2.parse("2.xml");
DOMDocument* doc2 = parser2.getDocument();

How can I know that doc1 and doc2 are identical from the xml point of view (i.e. they can have different spaces/end-of-lines/indentation, but represent same XML content)?

Upvotes: 0

Views: 502

Answers (1)

Yousha Aleayoub
Yousha Aleayoub

Reputation: 5703

You can serialize both documents to strings and then compare the strings.

This method ensures that the content of the XML documents is compared regardless of formatting differences like spaces, EOLs, or indentation.

Here's a simple code to achieve it:

#include <xercesc/dom/DOMImplementation.hpp>
#include <xercesc/dom/DOMWriter.hpp>
#include <xercesc/framework/LocalFileFormatTarget.hpp>

bool compareXMLDocuments(DOMDocument* doc1, DOMDocument* doc2)
{
    XMLCh tempStr[100];
    XMLString::transcode("LS", tempStr, 99);
    DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
    DOMWriter* writer = static_cast<DOMImplementationLS*>(impl)->createDOMWriter();
    XMLCh* xml1 = writer->writeToString(doc1);
    XMLCh* xml2 = writer->writeToString(doc2);
    bool isEqual = XMLString::equals(xml1, xml2);
    XMLString::release(&xml1);
    XMLString::release(&xml2);
    writer->release();
    return isEqual;
}

Upvotes: 0

Related Questions