首页 > 解决方案 > 循环 XML 中的比较

问题描述

我有xml,其中有一个循环。我想比较循环内的数据并获取状态,但当前的 xslt 不起作用。如何比较每个项目内的数据并获得我想要的状态?为什么我的 XSLT 不工作?

输入 XML

    <root>
    <a>123</a>
    <b>231</b>
    <c>
        <xxx>
            <qty>5</qty>
            <yyy>
                <ship>5</ship>
            </yyy>
        </xxx>
        <xxx>
            <qty>8</qty>
            <yyy>
                <ship>8</ship>
            </yyy>
        </xxx>
        <xxx>
            <qty>13</qty>
            <yyy>
                <ship>13</ship>
            </yyy>
        </xxx>
        <xxx>
            <qty>10</qty>
            <yyy>
                <ship>10</ship>
            </yyy>
        </xxx>
    </c>
</root>

XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>
    
    <xsl:template match="/root">
        <a>
            <xsl:choose>
                <xsl:when test="./c/xxx/qty != ./c/xxx/yyy/ship">Changed</xsl:when>
                <xsl:when test="./c/xxx/qty = ./c/xxx/yyy/ship">Accepted</xsl:when>
                <xsl:otherwise>Rejected</xsl:otherwise>
            </xsl:choose>
        </a>
    </xsl:template>
</xsl:stylesheet>

标签: xmlxslt

解决方案


假设您的问题有某种变体,您可以使用此样式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>
    
    <xsl:template match="/root">
        <a>
            <xsl:apply-templates select="*" />
        </a>
    </xsl:template>

    <xsl:template match="c/xxx[qty!=yyy/ship]">Changed</xsl:template>
    <xsl:template match="c/xxx[qty =yyy/ship]">Accepted</xsl:template>
    <xsl:template match="c[not(xxx)]">Rejected</xsl:template>

</xsl:stylesheet>

这个样式表假定有一个元素而不是<qty>一个<ship>元素。
如果没有xxx元素,你会得到REJECTED输出。


推荐阅读