微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

比较两个xml文件与xslt?

我有2个xml文件.如何使用xslt比较两个文件是否相等?如果不相等意味着在第二个xml中发生了哪些变化?
在XPath 2.0中,您可以简单地使用 fn:deep-equal.

遵循XSLT 1.0中的相同模式,此样式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:param name="pSource2" select="'emp2.xml'"/>
    <xsl:template match="/*">
        <xsl:variable name="vDeep-equal">
            <xsl:apply-templates select="." mode="deep-equal">
                <xsl:with-param name="pTarget" select="document($pSource2)/*"/>
            </xsl:apply-templates>
        </xsl:variable>
        <xsl:choose>
            <xsl:when test="normalize-space($vDeep-equal)">
                <xsl:text>Documents are different</xsl:text>
            </xsl:when>
            <xsl:otherwise>
                <xsl:text>Documents are deep equal</xsl:text>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
    <xsl:template match="*" mode="deep-equal">
        <xsl:param name="pTarget"/>
        <xsl:choose>
            <xsl:when test="$pTarget/self::* and
                            local-name()=local-name($pTarget) and
                            namespace-uri()=namespace-uri($pTarget) and
                            count(@*)=count($pTarget/@*) and
                            count(*|text()[normalize-space()]) =
                               count($pTarget/*|
                                     $pTarget/text()[normalize-space()])">
                <xsl:for-each select="@*">
                    <xsl:if test="$pTarget/@*[name()=name(current())] != .">
                        <xsl:text>false</xsl:text>
                    </xsl:if>
                </xsl:for-each>
                <xsl:for-each select="*|text()[normalize-space()]">
                    <xsl:variable name="vPosition" select="position()"/>
                    <xsl:apply-templates select="." mode="deep-equal">
                        <xsl:with-param name="pTarget"
                                        select="($pTarget/*|
                                                 $pTarget/text()
                                                    [normalize-space()])
                                                            [$vPosition]"/>
                    </xsl:apply-templates>
                </xsl:for-each>
            </xsl:when>
            <xsl:otherwise>false</xsl:otherwise>
        </xsl:choose>
    </xsl:template>
    <xsl:template match="text()" mode="deep-equal">
        <xsl:param name="pTarget"/>
        <xsl:if test="not($pTarget/self::text() and
                      string() = string($pTarget))">
            <xsl:text>false</xsl:text>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

输出

Documents are different

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。