Using an attribute value as part of an XPath query

Here should go questions about transforming XML with XSLT and FOP.
Posts: 1

Using an attribute value as part of an XPath query

Tue Oct 04, 2005 7:39 pm

I'm working with an XML file describing a database's metadata (i.e., just the tables and other structural elements and their relationships, not any data itself). It was generated by a commercial application and I do not have access to the DTD.

Is there a way given the following XML tree to get the Ref value "o16" and use it to find the o:Column element with an Id of the same value? I can do it when I specifically enter a static value in the XPath (ex. //o:Column[attribute::Id="o16"]), but need to be able to loop through any existing references using xsl:for-each (ex. //o:Column[attribute::Ref="X"] where X is the current value of Ref in the xsl:for-each). Ultimately I want to get //o:Column[attribute::Ref="X"]/a:Name

Code: Select all

               <o:Column Id="o16">
                           <o:Column Ref="o16">

Thanks for the help

Posts: 4144

Wed Oct 05, 2005 12:11 pm


A solution is to use a key to map the Ref attribute to the o:Column element with an Id attribute of the same value. The following example just output the string value of the a:Name element. Of course you have to replace o-namespace, c-namespace and a-namespace with your values.

Code: Select all

<xsl:stylesheet xmlns:xsl="" version="1.0" xmlns:o="o-namespace" xmlns:c="c-namespace" xmlns:a="a-namespace">
    <xsl:key name="columnId" match="o:Column" use="@Id"/>
    <xsl:template match="/">
        <xsl:for-each select="//o:Column[@Ref]">
           <!-- Here access the a:Name child of the o:Column element with the Id = @Ref. -->
           <!--  For that use: key('columnId', @Ref)/a:Name  -->
            <xsl:value-of select="key('columnId', @Ref)/a:Name"/>


Return to “XSLT and FOP”

Who is online

Users browsing this forum: No registered users and 2 guests