xml – XSLT xsl:for-each条件选择

前端之家收集整理的这篇文章主要介绍了xml – XSLT xsl:for-each条件选择前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一块看起来像这样的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,但只有tag2节点,其中subtag1是apple.我还需要每个序列号.

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

<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因为那时序列号对于第二个苹果来说是不准确的.

有任何想法吗?

谢谢,
里克

要保持代码,应该像下面这样简单:
<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>
原文链接:https://www.f2er.com/xml/292244.html

猜你在找的XML相关文章