我从两个不同的 Web 服务获取 XML 格式的响应。这两种 Web 服务具有相同的逻辑,但采用不同的技术开发。我们正在将我们的网络服务转向微软技术。 Web服务引擎是核心,它连接到许多其他应用程序并为它们提供不同的服务。
每当调用生产 Web 服务时,我们都会向基于 Microsoft 技术开发的 Web 服务传递类似的调用,并将两个响应保存在单独的文件夹中。
现在,我们必须比较两个响应 (XML)。有很多排序和意图问题。我想避免所有排序和缩进问题,以便获得正确的比较报告。
Is there a way you can sort and indent XML before saving (XMLDocument.Save) it?
谢谢。
解决方案:
我在网上找到了一些可以做到这一点的 XSLT,但似乎有一个 当元素具有属性时出现问题。
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-template select="@* | node()">
<xsl:sort select="name()"/>
</xsl:apply-template>
</xsl:copy>
</xsl:template>
事实上,属性节点必须在其他类型的任何节点之前复制到结果树中。由于排序,节点集丢失了文档顺序,因此无法再保证属性比元素和文本节点更早处理。
一个解决方案是这样的:
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@*">
<xsl:sort select="name()"/>
</xsl:apply-templates>
<xsl:apply-templates select="node()">
<xsl:sort select="name()"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
但是由于结果树序列化后属性的相对输出顺序取决于处理器,因此不妨省略属性排序:
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates select="node()">
<xsl:sort select="name()"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
感谢史努比和其他人的帮助!
最佳答案
我推荐使用 xmlunit 来比较文件,这个 nunit 扩展是用 C# 编写的,并且是免费的。 http://xmlunit.sourceforge.net/
或者如果您喜欢手动比较,可以这样做:
XmlDocument doc = new XmlDocument(); doc.LoadXml("bla"); XmlTextWriter writer = new XmlTextWriter("data.xml",null); writer.Formatting = Formatting.Indented; doc.Save(writer);
关于C#:如何在保存之前对 XML 进行排序和缩进?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6464636/