Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two XML files are the same in C#?

Tags:

c#

.net

xml

How do I check to see if two XML files are the same in C#?

I want to ignore comments in the XML file.

like image 955
Contango Avatar asked Nov 13 '13 12:11

Contango


People also ask

How can I tell if two XML files are the same?

By sorting them linewise and comparing, you can check if they are not equal. Of course, equal after sorting does not mean that they are really equal as sorting destroys the XML syntax.

Which of the following methods is used to compare two XML files?

The XMLUnit library can be used to compare two XML files in Java. Similar to JUnit, XMLUnit can also be used to test XML files for comparison by extending the XMLTestcase class. It is a rich library and provides a detailed comparison of XML files.

How do I compare two XML files in Visual Studio?

From the left Explorer panel, right-click the first file and choose Select for Compare from the right-click menu. Then right-click the second file and choose Compare with Selected. Both the files will be opened in the main panel, side by side in inline view mode which is comfortable for comparing the differences.


1 Answers

Install the free XMLDiffMerge package from NuGet. This package is essentially a repackaged version of the XML Diff and Patch GUI Tool from Microsoft.

This function returns true if two XML files are identical, ignoring comments, white space, and child order. As a bonus, it also works out the differences (see the internal variable differences in the function).

/// <summary>
/// Compares two XML files to see if they are the same.
/// </summary>
/// <returns>Returns true if two XML files are functionally identical, ignoring comments, white space, and child
/// order.</returns>
public static bool XMLfilesIdentical(string originalFile, string finalFile)
{
    var xmldiff = new XmlDiff();
    var r1 = XmlReader.Create(new StringReader(originalFile));
    var r2 = XmlReader.Create(new StringReader(finalFile));
    var sw = new StringWriter();
    var xw = new XmlTextWriter(sw) { Formatting = Formatting.Indented };

    xmldiff.Options = XmlDiffOptions.IgnorePI | 
        XmlDiffOptions.IgnoreChildOrder | 
        XmlDiffOptions.IgnoreComments |
        XmlDiffOptions.IgnoreWhitespace;
    bool areIdentical = xmldiff.Compare(r1, r2, xw);

    string differences = sw.ToString();

    return areIdentical;
}   

Here is how we call the function:

string textLocal = File.ReadAllText(@"C:\file1.xml");
string textRemote = File.ReadAllText(@"C:\file2.xml");
if (XMLfilesIdentical(textLocal, textRemote) == true)
{
    Console.WriteLine("XML files are functionally identical (ignoring comments).")
}
like image 78
Contango Avatar answered Sep 24 '22 23:09

Contango