How to compare XML files in C#?

帅比萌擦擦* 提交于 2019-11-28 23:41:31
James Johnson

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();
    }
}

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));

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

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