当 XSLT for-each 处于循环中时。如何根据其他 XML 值向该 XML 添加属性或节点。使用 XSLT

2024-01-03

任何人都可以帮我解决这个问题吗?

我有一个 XML 并根据某些条件过滤值。将过滤后的 xml 存储在变量中。在过滤条件时,我尝试向过滤后的 xml 添加属性或节点,但它对我不起作用。

输入 XML:

    <root>
        <a id="13">
            <b>XXX1</b>
            <c>YYY1</c>
        </a>
        <a id="2">
            <b>XXX2</b>
            <c>YYY2</c>
        </a>
        <a id="15">
            <b>XXX3</b>
            <c>YYY3</c>
        </a>
        <a id="37">
            <b>XXX4</b>
            <c>YYY4</c>
        </a>
        <a id="51">
            <b>XXX5</b>
            <c>YYY5</c>
        </a>
    </root>

另一个 XML 存储在名为“data”的变量中(用于过滤):

<sample>
    <con id="37" order="1"/>
    <con id="13" order="2"/>
    <con id="51" order="3"/>
    <con id="2" order="4"/>
    <con id="15" order="5"/>
</sample>

使用 XSLT,我尝试以这种方式过滤和添加元素。

<xsl:variable name="filteredData">
    <newroot>
      <xsl:for-each select="/root/a[@id > 14]">
        <xsl:if test="msxsl:node-set($data)/sample/con[@id = current()/@id]/@id = current()/@id">
          <xsl:element name="order">
            <xsl:value-of select="msxsl:node-set($data)/sample/con[@id = current()/@id]/@order"/>
          </xsl:element>
        </xsl:if>
      </xsl:for-each>
    </newroot>
</xsl:variable>

输出 XML(即“filteredData”变量应包含以下 XML):

     <newroot>
        <a id="15">
            <b>XXX3</b>
            <c>YYY3</c>
            <order>5</order>
        </a>
        <a id="37">
            <b>XXX4</b>
            <c>YYY4</c>
            <order>1</order>
        </a>
        <a id="51">
            <b>XXX5</b>
            <c>YYY5</c>
            <order>3</order>
        </a>
    </newroot>

尝试使用带有 key 函数的查找表,如本例所示提示:XSLT 查找表 http://www.ibm.com/developerworks/xml/library/x-xsltip.html

我能够获取以下代码片段来生成与上面的输出相匹配的 xml 文档。下面的 xslt 中的过滤数据是从单独的文档加载的,但应该很容易适应。

<xsl:key name="id-lookup" match="con" use="@id"/>

<xsl:variable name="id-top" select="document('<lookup file>')/sample"/>

<xsl:template match="root">
    <newroot>
        <xsl:for-each select="a[@id > 14]">
            <xsl:copy>
                <xsl:copy-of select="@*|node()"/>

                <xsl:element name="order">
                    <xsl:apply-templates select="$id-top">
                        <xsl:with-param name="curr-label" select="."/>
                    </xsl:apply-templates>
                </xsl:element>
            </xsl:copy>
        </xsl:for-each>
    </newroot>
</xsl:template>


<xsl:template match="sample">
    <xsl:param name="curr-label"/>
    <xsl:value-of select="key('id-lookup', $curr-label/@id)/@order"/>
</xsl:template>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当 XSLT for-each 处于循环中时。如何根据其他 XML 值向该 XML 添加属性或节点。使用 XSLT 的相关文章

随机推荐