How to Compare XML Strings Using .NET

So you want to compare two XML strings together to see if they are equal. Obviously, it would be easy to just compare the two strings using a regular string equality comparison and call it a day. However, what if the XML strings looked like the following:

<SampleXML>
    <SampleField1>Testing</SampleField1>
    <SampleField2 value="test value" />
    <SampleField3 type="int">456</SampleField3>
</SampleXML>
<SampleXML>
        <SampleField1>Testing</SampleField1>
    <SampleField2     value="test value" />
        <SampleField3 type="int">456</SampleField3></SampleXML>

All of the nodes, attributes and values are the same, but the formatting is way off. Obviously, a string equality comparison between these two would return false. Is there anything that can be done about this? Not to fear, .NET provides a pretty simple solution.

XmlDocument xmlDoc1 = new XmlDocument();
xmlDoc1.LoadXml(xmlString1);
                
XmlDocument xmlDoc2 = new XmlDocument();
xmlDoc2.LoadXml(xmlString2);

bool areXmlStringsEqual = xmlDoc1.OuterXml == xmlDoc2.OuterXml;

This method cleans up the XML strings and makes them in the same format. It’s a pretty simple solution that should find XML strings to be equal in most cases. For other cases, digging into the XmlDocument’s child node properties may be necessary, but that is a blog post for another day.

Richard Franzen
Developer
ImageSource, Inc.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s