簡體   English   中英

如何使用XSLT 1.0在某些條件下限制for-each循環?

[英]How to restrict a for-each loop with some condition using XSLT 1.0?

我有此XML代碼,我希望我的for循環僅運行/顯示特​​定類型num-10.20180的值

<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循環以檢查類型node-

<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運行一次。 如果類型20出現2次,我希望它每20次運行一次,然后轉到下一個180。因此總計應該運行3次,或者說我想打印一些與這3個值相關的詳細信息(因此應該不重復)。

您可以substring-after兩次substring-after使用substring-after檢查結尾num 不需要單獨的變量。

<xsl:for-each select="exslt:node-set($input)/*[starts-with(name(),'type-') and substring-after(substring-after(name(),'-'),'-') = 'num']">
  <xsl:value-of select="."/> </xsl:text>
</xsl:for-each>

輸出為:

1 2 4

如果只想匹配這些確切名稱,則可以直接選擇它們:

<xsl:for-each select="exslt:node-set($input)/*[self::type-10-num or self::type-20-num or self::type-180-num]">
  <xsl:value-of select="."/><xsl:text> </xsl:text>
</xsl:for-each>

輸出是相同的。

此轉換

<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>

為名稱類型為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="."/>

在解決特定問題上有什么必要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM