![]() |
|
|
|||||||
![]() |
XML - scoping to the first child element |
|
|
Thread Tools | Search this Thread |
|
|
#1 |
|
Given this XML
<parent> <child name="billy"> <child name="sue"> </parent> I can use this to process each child... <xsl:for-each select="child"> <xsl:value-of select="@name" /> </xsl:for-each> but if I want to only output info from the first child, I need to use this... <xsl:value-of select="child/@name" /> Is there some way to scope to the first child like this... <xsl:first select="child"> <xsl:value-of select="@name" /> </xsl:first> obviously, this is a contrived example but imagine if child had 40 attributes... <xsl:value-of select="child/@name" /> <xsl:value-of select="child/@age" /> <xsl:value-of select="child/@haircolor" /> <xsl:value-of select="child/@eyecolor" /> etc... It seems like there should be a way to avoid having to prefix the XPath for each select with "child/". William Krick |
|
|
|
|
#2 |
|
Posts: n/a
|
Positional predicate:
<xsl:first select="child[1]"> |
|
|
|
#3 |
|
Posts: n/a
|
Joe Kesselman wrote:
> Positional predicate: > <xsl:first select="child[1]"> there is no xsl:first tag. I made that up to illustrate what I need. though, I took your idea and came up with this... <xsl:for-each select="child[1]"> <xsl:value-of select="@name" /> <xsl:value-of select="@age" /> <xsl:value-of select="@haircolor" /> <xsl:value-of select="@eyecolor" /> </xsl:for-each> .... and it works but it seems kinda hacky to use a loop as there will only ever be one child[1] |
|
|
|
#4 |
|
Posts: n/a
|
William Krick wrote:
> ... and it works but it seems kinda hacky to use a loop as there will > only ever be one child[1] A good processor will recognize this usage pattern and not bother examinining anything after the first, so it's a perfectly reasonable way to express the problem. An alternative that doesn't look like a loop would be to assign the results of the child[1] search to a variable, then do the other expressions relative to that... <xsl:variable name="foo" select="child[1]"/> <xsl:value-of select="$foo/@name"> and so on. Or use a named template, applying it to select="child[1]". search. There are probably other equivalent solutions. XSLT is a programming language. There are often multiple ways to express an operation. Pick the one that matches what you're trying to express. |
|