Splitting Data Content

A somewhat common problem is splitting data from a single Element or Attribute in the source tree into two or more locations in the result tree. Let's again go back to our scenario of converting prospects to customers, but this time we'll assume that the contact management system has only a single field for the full name. (This is again somewhat of a contrived example, but I can't think of a better one right now.)

We want to turn this:

Source (CombinedContent.xml)
<?xml version="1.0" encoding="UTF-8"?>
<CombinedContent>
  <FullName>Fred Public</FullName>
</CombinedContent>

into this:

Result (SplitContent.xml)
<?xml version="1.0" encoding="UTF-8"?>
<SplitContent>
  <FirstName>Fred</FirstName>
  <LastName>Public</LastName>
</SplitContent>

Here's a template that does it.

Stylesheet (SplitContent.xsl)
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" version="1.0" encoding="UTF-8"
       indent="yes"/>
  <xsl:template match="/CombinedContent">
    <SplitContent>
      <FirstName>
        <xsl:value-of select="substring-before(FullName,' ')"/>
      </FirstName>
      <LastName>
        <xsl:value-of select="substring-after(FullName,' ')"/>
      </LastName>
    </SplitContent>
  </xsl:template>
</xsl:stylesheet>

The two xsl:value-of Elements in this example use a function for the expression value of the select Attribute. The substring-before and substring-after functions together work very much the same way that the string token functions do in Java or C/C++. We call substring-before to initialize, then succeeding calls to substring-after return succeeding tokens.

NOTE Real Stylesheets Are More Complicated!

Most of the transformations discussed in this and other sections would normally be coded as templates in a larger, more complex stylesheet. However, I handle the source fragments as complete documents and the stylesheets as complete, stand-alone stylesheets so that you may repeat and experiment with the transformations. You can find all the source documents and stylesheets on the book's Web site.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset