I come across a requirement for one of my projects where I need to check if two XML strings are equivalent. They might not be exact match (that would be too easy, a strings compare would do), nor have same namespaces, prefix and child order. Also, I want to be able to exclude certain nodes when comparing. I’m going to show how to achieve this using XmlDiffPatch.
Firstly, add the nuget package Microsoft.XmlDiffPatch to your project. Then, I create a method to check if two XML strings are equivalent as below
public bool AreXmlsEquivalent(string sourceXml, string expectedXml, params string[] excludedNodes)
{
var xmlSource = XDocument.Parse(sourceXml);
var xmlExpected = XDocument.Parse(expectedXml);
if(excludedNodes != null && excludedNodes.Length > 0)
{
xmlSource.Descendants().Where(x => excludedNodes.Contains(x.Name.LocalName)).Remove();
xmlExpected.Descendants().Where(x => excludedNodes.Contains(x.Name.LocalName)).Remove();
}
// See XmlDiffOptions for more information
var xmlDiff = new XmlDiff(XmlDiffOptions.IgnoreChildOrder |
XmlDiffOptions.IgnoreNamespaces |
XmlDiffOptions.IgnoreWhitespace |
XmlDiffOptions.IgnorePrefixes);
return xmlDiff.Compare(xmlSource.CreateReader(), xmlExpected.CreateReader());
}