Comparing XML string with different formats

Posted on

Problem

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?

Solution

Googling for xml compare c# produces countless results so I just review this code without suggesting anything alternative.


settings.IndentChars = "  ";

I find new string(' ', 3) is easier to understand then three (?) spaces.


    if (xmlA == null && xmlB == null)
        return true;

This is questionable. I’d say it should be false.


var settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;

Don’t you like object initializers?

var settings = new XmlWriterSettings
{
    OmitXmlDeclaration = true
};

Leave a Reply

Your email address will not be published. Required fields are marked *