Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Formatting an XML Document

To format planets.xml into planets.pdf, we can use the XSL-FO formatting objects that are introduced in Chapter 12. For example, here's how we might display the name of the first planet, Mercury, using XSL-FO formatting objects such as flow and block:

<fo:page-sequence master-name="page">
  <fo:flow flow-name="xsl-region-body">
<fo:block font-family="sans-serif" line-height="48pt"
      font-size="36pt" font-weight="bold">
      Mercury
    </fo:block>
    .
    .
    .

However, writing an entire document using the XSL formatting objects is not an easy task for any but short documents. W3C foresaw that difficulty, and that's one of the main reasons they introduced the transformation language, XSLT. In particular, you can write a stylesheet and use XSLT to transform an XML document so that it uses the XSL formatting objects.

In practice, using stylesheets is almost invariably the way such transformations are done, and it's the way we'll do things in Chapters 11 and 12. All you have to do is supply an XSLT stylesheet that can be used to convert your document to use formatting objects. In this way, an XSLT processor can do all the work for you, transforming a document from a form you're comfortable working with to formatting object form, which you can then feed to a program that can handle formatting objects and display the formatted result.

To make all this self-evident, here's an example using the XML document we've already seen in this chapter, planets.xml:

<?xml version="1.0"?>
<PLANETS>
  <PLANET>
    <NAME>Mercury</NAME>
    <MASS UNITS="(Earth = 1)">.0553</MASS>
    <DAY UNITS="days">58.65</DAY>
    <RADIUS UNITS="miles">1516</RADIUS>
    <DENSITY UNITS="(Earth = 1)">.983</DENSITY>
    <DISTANCE UNITS="million miles">43.4</DISTANCE><!--At perihelion-->
  </PLANET>

  <PLANET>
    <NAME>Venus</NAME>
    <MASS UNITS="(Earth = 1)">.815</MASS>
    <DAY UNITS="days">116.75</DAY>
    <RADIUS UNITS="miles">3716</RADIUS>
    <DENSITY UNITS="(Earth = 1)">.943</DENSITY>
    <DISTANCE UNITS="million miles">66.8</DISTANCE><!--At perihelion-->
  </PLANET>

  <PLANET>
    <NAME>Earth</NAME>
    <MASS UNITS="(Earth = 1)">1</MASS>
    <DAY UNITS="days">1</DAY>
    <RADIUS UNITS="miles">2107</RADIUS>
    <DENSITY UNITS="(Earth = 1)">1</DENSITY>
    <DISTANCE UNITS="million miles">128.4</DISTANCE><!--At perihelion-->
  </PLANET>
</PLANETS>

In this example, I'll use an XSLT stylesheet—which you'll see how to create in Chapter 11—to transform planets.xml so that it uses formatting objects. Then I'll use the FOP processor to turn the new document into a PDF file. I'll also take a look at the formatted document as it appears in Adobe Acrobat.

  • + Share This
  • 🔖 Save To Your Account