How to compare XML files in C#?

徘徊边缘 提交于 2019-12-29 04:48:20

问题


I know that there has been a lot of questions like this but I couldn't find a reply that would satisfy my needs. I have to write an application that will compare XML files: there will be 2 types of compare, first for 2 files, listing all the differences and second one for multiple XML files listing all the variations from averages.

I am looking for some kind of class, library or API that will help me finish this task. Can you suggest some solutions ?

And yet, I do not know if I should use DOM or Xpath. Any suggestions ?

EDIT:

Ok so I have been trying to accomplish this task with XmlDiff tool but this is quite problematic to solve this for multiple Xml files - I have no idea how can I use this XmlDiffDiagram to sort out the differences among for instance 50 Xml files.

Is it going to be better with LINQ ?


回答1:


Microsoft's XML Diff and Patch API should work nicely:

public void GenerateDiffGram(string originalFile, string finalFile, XmlWriter diffGramWriter)
{
   XmlDiff xmldiff = new XmlDiff(XmlDiffOptions.IgnoreChildOrder |
       XmlDiffOptions.IgnoreNamespaces | XmlDiffOptions.IgnorePrefixes);

   bool bIdentical = xmldiff.Compare(originalFile, finalFile, false, diffGramWriter);
   diffgramWriter.Close();
}

If you need to, you can also use the Patch tool to compare the files and merge them:

public void PatchUp(string originalFile, string diffGramFile, string outputFile)
{
    var doc = new XmlDocument();
    doc.Load(originalFile);

    using (var reader = XmlReader.Create(diffGramFile))
    {
        xmlpatch.Patch(sourceDoc, diffgramReader);

        using (var writer = XmlWriter.Create(outputFile))
        {
            doc.Save(writer);
            output.Close();
        }

        reader.Close();
    }
}



回答2:


If you want just to compare XML's and you don't need to get what is difference, you can use XNode.DeepEquals Method:

var xmlTree1 = new XElement("Root",
    new XAttribute("Att1", 1),
    new XAttribute("Att2", 2),
    new XElement("Child1", 1),
    new XElement("Child2", "some content")
);
var xmlTree2 = new XElement("Root",
    new XAttribute("Att1", 1),
    new XAttribute("Att2", 2),
    new XElement("Child1", 1),
    new XElement("Child2", "some content")
);
Console.WriteLine(XNode.DeepEquals(xmlTree1, xmlTree2));



回答3:


Personally, I would go with LINQ to XML. You can find a good tutorial at: http://msdn.microsoft.com/en-us/library/bb387061.aspx



来源:https://stackoverflow.com/questions/8096173/how-to-compare-xml-files-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!