scoping to the first child element

W

William Krick

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/".
 
W

William Krick

Joe said:
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]
 
J

Joe Kesselman

William said:
... 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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top