O'Reilly logo

XSLT Cookbook by Sal Mangano

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Deepening an XML Hierarchy

Problem

You have a poorly designed document that can use extra structure.[13]

Solution

This is the opposite problem from that solved in Recipe 6.7. Here you need to add additional structure to a document, possibly to organize its elements by some additional criteria.

Add structure based on existing data

This type of deepening transformation example undoes the flattening transformation performed in Recipe 6.7:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   
  <xsl:import href="copy.xslt"/>
  
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
  <xsl:strip-space elements="*"/>
   
  <xsl:template match="people">
    <union>
       <xsl:apply-templates select="person[@class = 'union']" />
    </union>
    <salaried>
       <xsl:apply-templates select="person[@class = 'salaried']" />
    </salaried>
  </xsl:template>  
   
</xsl:stylesheet>

Add structure to correct a poorly designed document

In a misguided effort to streamline XML, some people attempt to encode information by inserting sibling elements rather than parent elements.[14]

For example, suppose someone distinguished between union and salaried employees in the following way:

<people>
  <class name="union"/>
  <person>
    <firstname>Warren</firstname>
    <lastname>Rosenbaum</lastname>
    <age>37</age>
    <height>5.75</height>
  </person>
...
  <person>
    <firstname>Theresa</firstname>
    <lastname>Archul</lastname>
    <age>37</age>
    <height>5.5</height>
  </person>
  <class name="salaried"/> <person> <firstname>Sal</firstname> <lastname>Mangano</lastname> ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required