Page 1 of 1

Using an attribute value as part of an XPath query

Posted: Tue Oct 04, 2005 7:39 pm
by rxjones
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


<model>
<o:RootObject>
<c:Tables>
<o:Table>
<a:Name>
<c:Columns>
<o:Column Id="o16">
<a:Name>
<c:Indexes>
<o:Index>
<a:Name>
<c:IndexColumns>
<o:IndexColumn>
<c:Column>
<o:Column Ref="o16">
Thanks for the help

Roland

Posted: Wed Oct 05, 2005 12:11 pm
by sorin_ristache
Hello,

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="http://www.w3.org/1999/XSL/Transform" 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"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Regards,
Sorin