How to compare XML files in C#?(如何在 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 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C# 中比较 XML 文件?
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01