开发者

Using xslt get node value at X position

开发者 https://www.devze.com 2023-04-05 18:47 出处:网络
How can I get using xslt, node value at X position, without using foreach <items> <item1>x</item1>

How can I get using xslt, node value at X position, without using foreach

<items>
<item1>x</item1>
<item2>x</item2>
<item3>x</item3>
</items&g开发者_开发知识库t;

This is explained in programming sense:

<xsl:value-of select="Items/Item[2]"/>

==================================================

Just to little expand question, in the following xml:

<items>
    <about>xyz</about>
    <item1>
       <title>t1</title>
       <body>b1</body>
    </item1>
    <item2>
       <title>t2</title>
       <body>b2</body>
    </item2>
    <item3>
       <title>3</title>
       <body>3</body>
   </item3>
</items>

How can I select second's item title.


Answer to expanded question. You can use the positional value if you select a node-set of the wanted elements:

<xsl:value-of select="(items//title)[2]"/>

or:

<xsl:value-of select="(items/*/title)[2]"/>

Note the usage of the parenthesis required to return wanted node-set before selecting by position.


You can use what you called "in programming sense". However you need * due to the unknown name of the children elements:

<xsl:value-of select="items/*[2]"/>

Note that nodes-sets in XSLT are not zero-based. In the way above you are selecting the second item, not the third one.

You really need position() when you want compare the current position with a number as in:

<xsl:value-of select="items/*[position()>2]"/>

to select all item with position grater than 2. Other case where position() is indespensible is when position value is a variable of type string:

<xsl:variable name="pos" select="'2'"/>
<xsl:value-of select="items/*[position()=$pos]"/>


Just to little expand question, in the following xml:

<items> 
    <about>xyz</about> 
    <item1> 
       <title>t1</title> 
       <body>b1</body> 
    </item1> 
    <item2> 
       <title>t2</title> 
       <body>b2</body> 
    </item2> 
    <item3> 
       <title>3</title> 
       <body>3</body> 
   </item3> 
</items>

How can I select second's item title.

Use:

/*/*[starts-with(name(), 'item')][2]/title

This selects: all title elements that are children of the second of all children-elements of the top element, whose names are starting with the string "item".

Do note that expressions such as:

(items/*/title)[2]

or

(items//title)[2]

are not correct in general, because if in the XML document there are other elements such as (say) "chapter" that have title children, the above expressions could select an chapter/title element -- but the task here is to select the second title in the document whose parent could only be an itemXYZ element.


You can use position()

<xsl:value-of select="/items/*[position()=2]/text()"/>


You could do it with

<xsl:value-of select="items/child[position()=2]"/>
0

精彩评论

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

关注公众号