开发者

Selecting the first and second node in XSLT

Given the following structure, how to copy the first and the second nodes with all their elements from the document based on the predicate in XSLT:

<list>
  <slot>xx</slot>
   <data>
       <name>xxx</name>
       <age>xxx</age>  
   </data>      
   <data>
       <name>xxx</name>
       <age>xxx</age>  
   </data> 
   <data>
       <name>xxx</name>
       <age>xxx</age>  
   </data> 
</list> 
<list>
  <slot>xx</slot>
   <data>
       <name&g开发者_C百科t;xxx</name>
       <age>xxx</age>  
   </data> 
   <data>
       <name>xxx</name>
       <age>xxx</age>  
   </data> 
   <data>
       <name>xxx</name>
       <age>xxx</age>  
   </data> 
</list> 

How to select the first and the second occurence of data (without the data element itself, only name, age) from the list, where the slot is equal to a different variable, i.e the first list has the slot=02, but I need the data from the second list, where the slot=01. But it does not really matter the order of the list by a slot as long as slot=$slotvariable.

I tried the following statement, but it did not produce any results:

<xsl:element name="{'Lastdata'}">
  <xsl:copy-of select="list/data[position()=1 and slot = $slotvariable]" />
</xsl:element>
<xsl:element name="{'prevdata'}">
  <xsl:copy-of select="list/data[position()=2 and slot = $slotvariable]" />
</xsl:element>

Any working suggestions would be appreciated


If I understood your question correctly, then:

<Lastdata>
  <xsl:copy-of select="list[slot=$slotvariable]/data[1]/*" />
</Lastdata>
<prevdata>
  <xsl:copy-of select="list[slot=$slotvariable]/data[2]/*" />
<prevdata>

Hints:

  • Don't use <xsl:element> unless you have a dynamic name based on an expression.
  • [1] is a shorthand for [position() = 1]


The following stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:variable name="slot" select="'slot1'"/>
    <xsl:template match="/lists/list">
        <xsl:copy-of select="data[../slot=$slot][position()&lt;3]/*"/>
    </xsl:template>
</xsl:stylesheet>

Applied to this source:

<lists>
    <list>
      <slot>slot1</slot>
       <data>
           <name>George</name>
           <age>7</age>  
       </data> 
       <data>
           <name>Bob</name>
           <age>22</age>  
       </data> 
       <data>
           <name>James</name>
           <age>77</age>  
       </data> 
    </list> 
    <list>
      <slot>slot2</slot>
       <data>
           <name>Wendy</name>
           <age>25</age>  
       </data> 
    </list> 
</lists>

Produces the following result:

<name>George</name>
<age>7</age>
<name>Bob</name>
<age>22</age>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜