I need to compare 2 xml strings where the formatting may be different. The approach is to use the XmlWriterSettings
to format both strings and compare the formatted result:
public static class XmlHelper
{
public static string FormatXml(string xml)
{
try
{
var stringBuilder = new StringBuilder();
var element = XDocument.Parse(xml);
var settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
settings.IndentChars = " ";
settings.NewLineChars = Environment.NewLine;
settings.NewLineOnAttributes = false;
settings.NewLineHandling = NewLineHandling.Replace;
using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))
element.Save(xmlWriter);
return stringBuilder.ToString();
}
catch (Exception ex)
{
Logger.Error("Unable to format XML: '" + xml + "'", ex);
return xml;
}
}
public static bool CompareXml(string xmlA, string xmlB)
{
if (xmlA == null && xmlB == null)
return true;
if (xmlA == null || xmlB == null)
return false;
var xmlFormattedA = FormatXml(xmlA);
var xmlFormattedB = FormatXml(xmlB);
return xmlFormattedA.Equals(xmlFormattedB, StringComparison.InvariantCultureIgnoreCase);
}
}
My questions are:
- Do you see any problems with that approach?
- Is there a simpler way to accomplish that kind of comparison?