Subject: Re: [xsl] Selecting first descendant text node From: Jeni Tennison <jeni@xxxxxxxxxxxxxxxx> Date: Sat, 12 Jan 2002 11:59:46 +0000 |
Hi Christian, >>> how do I select the first descendant text node of an element? >> >>item//text()[count((ancestor::item[1]//text())[1] | .)=1] The count($node|.) = 1 pattern is a way of testing whether the context node is the same as $node. In XPath 2.0 it would be equivalent to $node == . So the above is equivalent to: (ancestor::item[1]/text())[1] == 1 in other words - "is this node the same node as the first text node descendant of this node's ancestor item?" Another way of approaching it would be to have a general template that matches text nodes within the item element, with a test inside that checks whether a number should be added: <xsl:template match="item//text()"> <xsl:variable name="nearestItem" select="ancestor::item[1]" /> <xsl:if test="count(($nearestItem//text())[1] | .) = 1"> <xsl:value-of select="$nearestItem/@numbertext" /> </xsl:if> <xsl:value-of select="." /> </xsl:template> Another method would be to pass through the numbertext as a parameter, but only pass it on (or do anything else with it) if the node has no preceding siblings. When you applied templates from the item element, pass the value of the numbertext attribute as a parameter: <xsl:template match="item"> <item> <xsl:apply-templates> <xsl:with-param name="numbertext" select="@numbertext" /> </xsl:apply-templates> </item> </xsl:template> Then have a template for element descendants of item that only passes on the parameter if it's the first child of its parent: <xsl:template match="item//*"> <xsl:param name="numbertext" /> <xsl:copy> <xsl:choose> <xsl:when test="not($numbertext) or preceding-sibling::*"> <xsl:apply-templates /> </xsl:when> <xsl:otherwise> <xsl:apply-templates> <xsl:with-param name="numbertext" select="$numbertext" /> </xsl:apply-templates> </xsl:otherwise> </xsl:choose> </xsl:copy> </xsl:template> Finally have a template for text node descendants of the item element - if it receives a value for the $numbertext parameter at all then it's because it's the first text node descendant: <xsl:template match="text()"> <xsl:param name="numbertext" /> <xsl:value-of select="$numbertext" /> <xsl:value-of select="." /> </xsl:template> [You can safely just give the value of $numbertext because if nothing's passed through it defaults to an empty string, which gives no value anyway.] Cheers, Jeni --- Jeni Tennison http://www.jenitennison.com/ XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list
Current Thread |
---|
|
<- Previous | Index | Next -> |
---|---|---|
RE: [xsl] Selecting first descendan, Christian Roth | Thread | Re: [xsl] Selecting first descendan, Wendell Piez |
RE: Regular expression functions (W, Marc Portier | Date | Re: Regular expression functions (W, Jeni Tennison |
Month |