简体   繁体   English

比较C#中的两个XmlNode

[英]Compare two XmlNodes in C#

Is there a simple way to compare two XML structures to determine if they have the same structure and data? 有没有一种简单的方法来比较两个XML结构,以确定它们是否具有相同的结构和数据?

I have a function that returns an XmlNode and I am trying to write unit tests for it. 我有一个返回XmlNode的函数,我正在尝试为它编写单元测试。 I store the correct XML result in a file. 我将正确的XML结果存储在一个文件中。 Durring the test I load the file into an XmlDocument, locate the proper XmlNode and compare against the result of the function. 在测试中,我将文件加载到XmlDocument中,找到正确的XmlNode并与函数的结果进行比较。 A straight compare does not work (as expected) and InnerXml does not work either. 直接比较不起作用(如预期的那样),而且InnerXml也不起作用。 I am considering removing all whitespace from InnerXml and comparing that, or writing my own compare to walk the tree, but I don't like either option much. 我正在考虑从InnerXml中删除所有空格并比较它,或者编写我自己的比较来走树,但我不喜欢这两个选项。

XNode.DeepEquals . XNode.DeepEquals Read the caveats before using it. 在使用之前阅读警告。

Like CodeToGlory answered, XNode.DeepEquals() might fit your bill, check the remarks section on the MSDN page. 与CodeToGlory一样,XNode.DeepEquals()可能适合您的帐单,请查看MSDN页面上的备注部分。

If you are stuck with XmlDocument (instead of XDocument), the answer is: No, there is no simple (existing way) to do it. 如果你坚持使用XmlDocument(而不是XDocument),答案是:不,没有简单的(现有方法)来做到这一点。 XmlNode does not override Equals(), or provide an alternative. XmlNode不会覆盖Equals(),或提供替代方法。 But it is not impossible to write, and that same Remarks section can be used as a starting point for a tree-walk algorithm. 但是编写并不是不可能,并且相同的备注部分可以用作树木行走算法的起点。

Do get a clear picture of your requirements first, concerning Attributes, comments, CDATA nodes etc. 首先要清楚了解您的要求,包括属性,注释,CDATA节点等。

如果必须使用XmlDocument及其支持类型,请考虑使用Microsoft的XmlDiffPatch ,它在XML数据结构上执行可自定义的diff操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM