首页 > 解决方案 > 如何使用 XSLT 1.0 在某些条件下限制 for-each 循环?

问题描述

我有这个 XML 代码,我希望我的 for 循环只运行/显示特​​定类型 num- 10,20,180 的值

<input>
<name>Jack</name>
<age>23</age>
<type-10-num>1</type-10-num>
<type-20-num>2</type-20-num>
<type-20-char>3</type-20-char>
<type-180-num>4</type-180-num>
<type-180-char>5</type-180-char>
<type-180-str>6</type-180-str>
</input>

我正在运行一个 for-each 循环来检查类型节点-

<xsl:for-each select="exslt:node-set($input)/*[starts-with(name(),'type-')]">

并在变量中从中获取类型值-

 <xsl:variable name="fetchValue">               
                        <xsl:value-of select="substring-before(substring-after(name(), '-'), '-')" />                   
                    </xsl:variable>

但我希望我的 for 循环为每个值 10,20,180 运行一次。如果 type-20 出现 2 次,我希望它每 20 运行一次,然后转到下一个 180。所以总共它应该运行 3 次,或者说我想打印与这 3 个值相关的一些细节(所以它应该不再重复)。

标签: xmlxslt-1.0

解决方案


这种转变

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

  <xsl:template match=
        "*[starts-with(name(), 'type-')
         and substring(name(), string-length(name())-2) = 'num'
         ]">
    <xsl:copy-of select="."/>
  </xsl:template>

  <xsl:template match="text()"/>
</xsl:stylesheet>

当应用于提供的 XML 文档时(为便于阅读而格式化):

<input>
    <name>Jack</name>
    <age>23</age>
    <type-10-num>1</type-10-num>
    <type-20-num>2</type-20-num>
    <type-20-char>3</type-20-char>
    <type-180-num>4</type-180-num>
    <type-180-char>5</type-180-char>
    <type-180-str>6</type-180-str>
</input>

为每个名为type-XYZ-num的元素生成数据:

<type-10-num>1</type-10-num>
<type-20-num>2</type-20-num>
<type-180-num>4</type-180-num>

可以在匹配的模板中替换此代码:

<xsl:copy-of select="."/>

解决特定问题所需的一切。


推荐阅读