首页 > 解决方案 > How to check equivalence of two XML documents?

问题描述

From my program I call a command line XSLT processor (such Saxon or xsltproc).

Then (for testing purposes) I want to compare the output of the processor with a predefined string.

The trouble is that XML can be formatted differently. The following three are different strings:

<?xml version="1.0" encoding="utf-8"?>
<x/>

<?xml version="1.0"?>
<x/>

<?xml version="1.0"?>
<x
/>

How to check output from different XSLT processors to match a given XML string?

Maybe there is a way (not necessarily standartized) for different XSLT processors to output exactly the same?

I use Python 3.

标签: pythonxmlpython-3.xxslt

解决方案


您是否考虑过使用像 XSpec 这样已经解决了这个问题的测试框架?

通常,解决此问题的两种经典方法是在将序列化的 XML 放入规范化器之后对其进行词法比较,或者使用诸如 XPath 2.0 deep-equal() 之类的函数比较树表示。

这些都不是一个完美的答案。首先,XML 规范化认为重要或不重要的事情可能与您认为重要或不重要的事情不同;XPath 也是如此deep-equal()。其次,您不仅想知道文件是否相同,还想知道不同之处在哪里。

Saxon 有一个增强版的deep-equal()calledsaxon:deep-equal()旨在解决这些问题:它采用一组可用于自定义比较的标志,并试图告诉您在警告消息方面的差异在哪里。但这也不是一个完美的解决方案。

在用于 XSLT 3.0 和 XQuery 的 W3C 测试套件中,我们已经从比较测试的 XML 输出转向针对 XPath 表达式的预期结果编写断言。测试使用这样的断言:

  <result>
     <all-of>
        <assert>every $a in /out/* except /out/a4 
                satisfies $a/@actual = $a/@expected</assert>
        <assert>/out/a4/@actual = 'false'</assert>
     </all-of>
  </result> 

推荐阅读