如何在 Ruby 中测试 XML 相等性?
显然我需要 (a) 将两个字符串都转换为 规范 XML 或 (b) 比较它们的解析树.以下不起作用,因为返回的文档对象没有定义合理的 ==
.
Clearly I need to (a) convert both strings to canonical XML or (b) compare their parse-trees. The following doesn't work because the document object returned doesn't have a sensible ==
defined.
Nokogiri.XML(doc_a) == Nokogiri.XML(doc_b)
以下也不行,因为 Nokogiri 的 to_xml
留下了一些内部空白:
Nor does the following, because Nokogiri's to_xml
leaves some internal whitespace:
Nokogiri.XML(doc_a).to_xml == Nokogiri.XML(doc_b).to_xml
这是平等的合理近似(并且适用于大多数情况),但并不完全正确:
This is a reasonable approximation of equality (and will work for most cases), but it's not quite right:
Nokogiri.XML(doc_a).to_xml.squeeze(' ') == Nokogiri.XML(doc_b).to_xml.squeeze(' ')
我已经在使用 Nokogiri,所以我更愿意坚持使用它,但我会使用任何可用的库.
I'm already using Nokogiri, so I'd prefer to stick with it, but I'll use whatever library works.
如果您正在寻找结构上的相等性并且不关心标签和属性的顺序,那么 xml-simple 库是一个不错的选择.它将 xml 转换为 ruby 的数据结构(散列和列表),可以安全地与 ==
运算符进行比较.
If you are looking for structural equality and don't care about the order of tags and attributes, probably the xml-simple library is a good choice. It converts the xml into ruby's data structures (hashes and lists) which can be safely compared with the ==
operator.