...

View Full Version : XPath select first child element



Jazzo
11-02-2008, 01:48 PM
How would I select the first child element of an element. For example:


<parent>
<child1>x</child1>
<child2>y</child2>
<child3>z</child3>
</parent>


I want to select <child1> but I don't know what it is.

oesxyl
11-02-2008, 03:05 PM
How would I select the first child element of an element. For example:


<parent>
<child1>x</child1>
<child2>y</child2>
<child3>z</child3>
</parent>


I want to select <child1> but I don't know what it is.
this could work:


parent/*[1]

a condition must be inside of '[' and ']' and could use some function like position(), for example:


parent/*[psotion() = 1] is same as parent/*[1]
parent/*[last]
parent/*[name() = 'child2']


see the xpath tutorial from the link I post in one of my answer to your posts.

best regards

Jazzo
11-02-2008, 04:53 PM
That's what I tried but the problem is, it's within a for-each element. Like this:

<xsl:for-each select="parent">
<xsl:value-of select="The first child element of 'parent.'"/>

How would I do that?

oesxyl
11-02-2008, 05:23 PM
That's what I tried but the problem is, it's within a for-each element. Like this:

<xsl:for-each select="parent">
<xsl:value-of select="The first child element of 'parent.'"/>

How would I do that?
few way to do same thing:
1.)


<xsl:for-each select="parent">
<xsl:value-of select="*[1]"/>
</xsl:for-each>


2.)


<xsl:for-each select="parent">
<xsl:if test="position() = 1">
</xsl:value-of select="*"/>
</xsl:if>
</xsl:for-each>


3.)


<xsl:apply-template select="parent/*[1]" mode="mymode"/>

<xsl:template match="*" mode="mymode">
<xsl:value-of select="*"/>
</xsl:template>


I prefere 3.)

best regards

Jazzo
11-02-2008, 05:36 PM
It works, thank you :)

oesxyl
11-02-2008, 05:39 PM
It works, thank you :)
you are welcome, :) always, :)

best regards



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum