kawadw
kawadw

Reputation: 45

xml file comparison

Is there any way to compare two XML files in C#? I only want to compare the nodes of the first file with that of of second file. I don't want to append the missing nodes.

Is there any way to do this?

Here's what I have tried:

var docA = XDocument.Parse(@"<mind_layout></mind_layout>");
var docB = XDocument.Parse(@"<mind_layout></mind_layout>");

var rootNameA = docA.Root.Name;
var rootNameB = docB.Root.Name;
var equalRootNames = rootNameB.Equals(rootNameA);

var descendantsA = docA.Root.Descendants();
var descendantsB = docB.Root.Descendants();
for (int i = 0; i < descendantsA.Count(); i++)
{
    var descendantA = descendantsA.ElementAt(i);
    var descendantB = descendantsB.ElementAt(i);
    var equalChildNames = descendantA.Name.Equals(descendantB.Name);

    var valueA = descendantA.Value;
    var valueB = descendantA.Value;
    var equalValues = valueA.Equals(valueB);
}

where <mind_layout> is the root node in both the files.

Upvotes: 1

Views: 1623

Answers (1)

Xavier Poinas
Xavier Poinas

Reputation: 19733

If you just want to compare the file contents (including, for example, indentation), you coud do:

if (File.ReadAllText(@"C:\path\to\file1.xml") == File.ReadAllText(@"C:\path\to\file2.xml"))
{
    // Same TEXT content
}

(Warning: this is not the most optimized check you could do!)

If you want to compare the XML content (regardless of the formatting), you can do:

var doc1 = XDocument.Load(File.OpenRead(@"C:\path\to\file1.xml"));
var doc2 = XDocument.Load(File.OpenRead(@"C:\path\to\file2.xml"));

if (XDocument.DeepEquals(doc1, doc2))
{
    // Same XML content
}

Upvotes: 1

Related Questions