2
\$\begingroup\$

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?
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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
};
\$\endgroup\$
1
  • \$\begingroup\$ Thanks for the feedback. a) agree (they are actual 2 spaces ;)) b) Yes, that is questionable (and it is very unlikely that the case occurs someday)... however, string.Equals(null, null) is true, therefore I think the result should be true as well . c) I like it too... changed the impl. :) \$\endgroup\$
    – JanDotNet
    Oct 10, 2016 at 13:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.