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?
asked Oct 10, 2016 at 13:20
\$\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
};
answered Oct 10, 2016 at 13:41
\$\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\$ Commented Oct 10, 2016 at 13:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.