Link multiple elements from source XML data

An interesting question was asked in the Sun's Java forums: “How do I match attributes on different input nodes?” For example, I would like to link the target attribute of the source element in the following XML data with the target node (based on the num attribute of its id child).
<data>
  <source id="abc" target="123" />
 
  <target>
     <text>Message</text>
     <id num="123" />
  </target>
</data>
While it's easy to select the correct target node, it's harder to get the source attribute into the XPath expression; the only way to do it is to store the source attribute in a local variable and then use the variable value (which is context-independent) in the XPath expression:
<xsl:template match="source">
  <xsl:variable name="target" select="@target" />
  Source <xsl:value-of select="@id" />
    is associated with
  <xsl:value-of select="//target[id/@num = $target]/text" />
</xsl:template>
The final XPath expression works as follows:
  • It selects a target node anywhere in the source XML tree (the // path) such that the num attribute of its id child is equal to the local variable target
  • When the target node is selected, the value of the XPath expression is the value of its text child, which is then rendered into a string (collapsing all its descendant text nodes into the final result).

This post is part of You've asked for it series of articles.

No comments:

Post a Comment