XSLT xsl:for-each条件选择

时间:2011-06-15 14:17:00

标签: xml xslt

我有一块看起来像这样的xml:

<root>
  <tag1>tractor</tag1>
  <tag2>
    <subtag1 att="apple" />
    <subtag2>
      <subsubtag1>red</subsubtag1>        
      <subsubtag2>lunch</subsubtag2>
    </subtag2>
  </tag2>      
  <tag1>forklift</tag1>
  <tag2>
    <subtag1 att="pear" />
    <subtag2>
      <subsubtag1>green</subsubtag1>        
      <subsubtag2>breakfast</subsubtag2>
    </subtag2>
  </tag2>      
  <tag2>
    <subtag1 att="apple" />
    <subtag2>
      <subsubtag1>green</subsubtag1>        
      <subsubtag2>dinner</subsubtag2>
    </subtag2>
  </tag2>   
  <tag1>combine harvester</tag1>
</root>

我需要对其进行转换,以便从每个tag2节点获取子标记2和3,但只获取subtag1为apple的tag2节点。我还需要每个序列号。

我当前的代码看起来像这样:

<xsl:for-each select="//tag2">
  <apple>
    <seq_num><xsl:value-of select="position()" /></seq_num>
    <colour><xsl:value_of select="subtag2" /></colour>  
    <meal><xsl:value_of select="subtag3" /></meal>  
  </apple>
</xsl:for-each>

这没关系,除了我需要for-each只返回tag2,它们是苹果(即subtag1 = apple)。我不能使用xsl:if或xsl:when因为那时序列号对于第二个苹果来说是不准确的。

有什么想法吗?

谢谢, 瑞克

1 个答案:

答案 0 :(得分:13)

要使用您的代码,应该像下面这样简单:

<xsl:for-each select="//tag2[subtag1/@att='apple']">
  <apple>
    <seq_num><xsl:value-of select="position()" /></seq_num>
    <colour><xsl:value-of select="subtag2/subsubtag1" /></colour>  
    <meal><xsl:value-of select="subtag2/subsubtag2" /></meal>  
  </apple>
</xsl:for-each>

根据以下评论,如建议的那样,最好避免使用//。你应该能够在正确的背景下。例如:

<xsl:stylesheet   version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/root">
        <xsl:for-each select="tag2[subtag1/@att='apple']">
            <apple>
                <seq_num><xsl:value-of select="position()" /></seq_num>
                <colour><xsl:value-of select="subtag2/subsubtag1" /></colour>  
                <meal><xsl:value-of select="subtag2/subsubtag2" /></meal>  
            </apple>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

在您的输入上显示,产生相同的结果。或者更好,也可以避免使用xsl:for-each

<xsl:stylesheet   version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/root">
        <xsl:apply-templates select="tag2[subtag1/@att='apple']"/>
    </xsl:template>

    <xsl:template match="tag2">
        <apple>
            <seq_num><xsl:value-of select="position()" /></seq_num>
            <colour><xsl:value-of select="subtag2/subsubtag1" /></colour>  
            <meal><xsl:value-of select="subtag2/subsubtag2" /></meal>  
        </apple>
    </xsl:template>

</xsl:stylesheet>