Performing Structure-Preserving Queries

Problem

You need to query an XML document so that the response has a structure that is identical to the original.

Solution

Structure-preserving queries filter out irrelevant information while preserving most of the document structure. The degree by which the output structure resembles the structure of the input is the metric that determines the applicability of this example. The more similar it is, the more this example applies.

The example has two components—one reusable and the other custom. The reusable component is a stylesheet that copies all nodes to the output (identity transform). We used this stylesheet, shown in Example 7-9, extensively in Chapter 6.

Example 7-9. copy.xslt

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   
<xsl:template match="/ | node(  ) | @*">
  <xsl:copy>
    <xsl:apply-templates select="@*"/>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>
   
</xsl:stylesheet>

The custom component is a stylesheet that imports copy.xslt and creates rules to override its default behavior. For example, the following stylesheet results in output identical to people.xml, but with only female smokers:

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:import href="copy.xslt"/> <!-- Collapse space left by removing person elements --> <xsl:strip-space elements="people"/> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> ...

Get XSLT Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.