How to compare XML files in C#?

后端 未结 3 1494
萌比男神i
萌比男神i 2020-12-15 09:37

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:

相关标签:
3条回答
  • 2020-12-15 10:26

    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)
        {
            XmlDocument sourceDoc = new XmlDocument(new NameTable());
            sourceDoc.Load(originalFile);
    
            using (var reader = XmlReader.Create(diffGramFile))
            {
                XmlPatch xmlPatch = new XmlPatch();
                xmlPatch.Patch(sourceDoc, reader);
    
                using (var writer = XmlWriter.Create(outputFile))
                {
                    sourceDoc.Save(writer);
                    writer.Close();
                }
                reader.Close();
            }
        }
    
    0 讨论(0)
  • 2020-12-15 10:32

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

    0 讨论(0)
  • 2020-12-15 10:38

    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));
    
    0 讨论(0)
提交回复
热议问题