ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Fetching information across in-document references
Submitter: Paul Prescod (other recipes)
Last Updated: 2001/06/25
Version no: 1.0
Category: Hyperlinks and URLs

 

4 stars 2 vote(s)


Approved

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.



Add comment

No comments.



Highest rated recipes:

1. Search and Replace

2. Generating a newline

3. Internationalization ...

4. Restricting processing ...

5. Result Pagination with ...

6. Fetching information ...

7. Getting text children of ...

8. Creating empty elements




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.