|
Description:
XML documents often contain references from one type of element
(e.g. chapter-ref) to another (e.g. chapter). This recipe shows how to
reach into those other elements to get information.
Source: Text Source
XML Input:
<?xml version="1.0"?>
<book>
<chapter id="first-chapter" security="high">
<title>Chapter title 1</title>
... more info in <chapter-ref refid="second-chapter"/>
</chapter>
<chapter id="second-chapter" security="low">
<title>Chapter title 2</title>
... as we discussed in <chapter-ref refid="first-chapter"/>
</chapter>
</book>
XSL Stylesheet:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="chapter-ref">
<xsl:variable name="target-id" select="@refid"/>
<xsl:variable name="target-chapter" select="//chapter[@id=$target-id]"/>
Chapter "<xsl:value-of select="$target-chapter/title"/>"
(security level: <xsl:value-of select="$target-chapter/@security"/>)
</xsl:template>
</xsl:stylesheet>
The license for this recipe is available here.
Discussion:
Note that the recipe stores away the target id in a variable. This will not work:
"//chapter[@id=@refid]"
That will search for a chapter with "id" and "refid" attributes that are equal. Instead we want the chapter-ref's "refid" to equal the chapter's "id". There are other ways to solve that problem but this one is nice and simple.
Once we have a handle to the chapter in "target-chapter" we can get any informatoin around it that we need: attributes, sub-elements even parents or sibling elements.
|