如何在 C# 中比较 XML 文件? [英] How to compare XML files in C#?

查看:34
本文介绍了如何在 C# 中比较 XML 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多这样的问题,但我找不到能满足我需求的答复.我必须编写一个比较 XML 文件的应用程序:将有 2 种比较类型,第一种用于 2 个文件,列出所有差异,第二种用于多个 XML 文件,列出平均值的所有变化.

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.

我正在寻找某种类、库或 API 来帮助我完成这项任务.你能提出一些解决方案吗?

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

然而,我不知道我应该使用 DOM 还是 Xpath.有什么建议 ?

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

好的,所以我一直在尝试使用 XmlDiff 工具来完成这项任务,但是对于多个 Xml 文件来说解决这个问题非常有问题 - 我不知道如何使用这个 XmlDiffDiagram 来整理出例如 50 个 Xml 文件之间的差异.

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.

使用 LINQ 会更好吗?

Is it going to be better with LINQ ?

推荐答案

微软的 XML Diff and Patch API 应该可以很好地工作:

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

这篇关于如何在 C# 中比较 XML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆