[XSL-LIST Mailing List Archive Home] [By Thread] [By Date]

Re: [xsl] XSL/XPath to generate a list of ancestors?


Subject: Re: [xsl] XSL/XPath to generate a list of ancestors?
From: Martin Honnen <Martin.Honnen@xxxxxx>
Date: Mon, 12 May 2008 18:03:25 +0200

Nathan Potter wrote:

I need to concatenate the "name" attributes of all of the parents for each element. All I could figure out was to use a recursive template. Is there a more straightforward way to accomplish this?




XML:

<Dataset name="root">
    <A name="a1">
        <A name="a2">
            <A name="a3" />
        </A>
    </A>
    <B name="b1">
        <B name="b2"/>
    </B>
</Dataset>

Desired output:

<fullName>a1</fullName>
<fullName>a1.a2</fullName>
<fullName>a1.a2.a3</fullName>

<fullName>b1</fullName>
<fullName>b1.b2</fullName>

So you want to exclude the root element 'Dataset' although it has a name attribute. Then the following should do:


<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

<xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <xsl:apply-templates select="*//*"/>
  </xsl:template>

<xsl:template match="*">
<fullName>
<xsl:for-each select="ancestor-or-self::*[not(generate-id() = generate-id(/*))]/@name">
<xsl:value-of select="."/>
<xsl:if test="position() != last()">
<xsl:text>.</xsl:text>
</xsl:if>
</xsl:for-each>
</fullName>
</xsl:template>


</xsl:stylesheet>
--

	Martin Honnen
	http://JavaScript.FAQTs.com/


Current Thread