Using xslt get node value at X position

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-03 17:50:37

问题


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>

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.


回答1:


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]"/>



回答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.

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.




回答3:


You can use position()

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



回答4:


You could do it with

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


来源:https://stackoverflow.com/questions/7455583/using-xslt-get-node-value-at-x-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!