您将如何比较两个 XML 文档? [英] How would you compare two XML Documents?

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

问题描述

作为一些广泛单元测试的基类的一部分,我正在编写一个辅助函数,它递归地比较一个 XmlDocument 对象的节点与 C# (.NET) 中的另一个.对此的一些要求:

As part of the base class for some extensive unit testing, I am writing a helper function which recursively compares the nodes of one XmlDocument object to another in C# (.NET). Some requirements of this:

  • 第一个文档是来源,例如我希望 XML 文档看起来像什么.因此,第二个是我想要找到差异的那个,它不能包含不在第一个文档中的额外节点.
  • 当发现太多显着差异时必须抛出异常,并且应该很容易让人类浏览一下描述就能理解.
  • 子元素顺序很重要,属性可以是任意顺序.
  • 有些属性是可以忽略的;特别是 xsi:schemaLocationxmlns:xsi,虽然我希望能够传递哪些是.
  • 命名空间的前缀必须在属性和元素中匹配.
  • 元素之间的空白是无关紧要的.
  • 元素将要么有子元素InnerText,但不能同时有.
  • The first document is the source, e.g. what I want the XML document to look like. Thus the second is the one I want to find differences in and it must not contain extra nodes not in the first document.
  • Must throw an exception when too many significant differences are found, and it should be easily understood by a human glancing at the description.
  • Child element order is important, attributes can be in any order.
  • Some attributes are ignorable; specifically xsi:schemaLocation and xmlns:xsi, though I would like to be able to pass in which ones are.
  • Prefixes for namespaces must match in both attributes and elements.
  • Whitespace between elements is irrelevant.
  • Elements will either have child elements or InnerText, but not both.

虽然我正在整理一些东西:有没有人写过这样的代码,可以在这里分享吗?

While I'm scrapping something together: has anyone written such code and would it be possible to share it here?

顺便说一句,你会怎么称呼第一个和第二个文件?我一直将它们称为源"和目标",但感觉不对,因为 是我希望 目标 的样子,否则我会抛出一个例外.

On an aside, what would you call the first and second documents? I've been referring to them as "source" and "target", but it feels wrong since the source is what I want the target to look like, else I throw an exception.

推荐答案

Microsoft 有一个 您可以使用的>XML diff API.

Microsoft has an XML diff API that you can use.

非官方 NuGet:https://www.nuget.org/packages/XMLDiffPatch.

Unofficial NuGet: https://www.nuget.org/packages/XMLDiffPatch.

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

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