Inside Xslt

The <?xsl:stylesheet?> Processing Instruction

When you have an XSL stylesheet you want to apply to an XML document, you need some way of connecting that stylesheet to the document, and thats often done with the <?xsl:stylesheet?> processing instruction. This instruction has several possible attributes:

The <?xsl:stylesheet?> processing instruction is added in the XML document, not the XSL stylesheet, and shows XSLT processors which stylesheet to use with this document.

In practice, <?xsl:stylesheet?> is used mostly with browsers, because with standalone processors, you usually give the name of the stylesheet document directly, as when you use the Oracle XSLT processor this way:

C:\planets>java oracle.xml.parser.v2.oraxsl planets.xml planets.xsl planets.html

In fact, it may surprise you to learn that <?xsl:stylesheet?> is not part of the XSLT recommendation. This processing instruction has its own recommendation just for itself, which you can find at www.w3c.org/TR/xml-stylesheet. Among other things, this means that XSLT processors are not obliged to support this processing instruction, and most standalone processors do not.

Heres an example. In Chapter 1, you saw planets.xml, a well- formed XML document that holds data about three planets: Mercury, Venus, and the Earth. You can use the <?xml-stylesheet?> processing instruction in planets.xml to indicate what XSLT stylesheet to use, where you set the type attribute to text/xml (W3C also allows application/xml, and the Internet Explorer requires text/xsl) and the href attribute to the URI of the XSLT stylesheet, such as planets.xsl:

Listing 2.1 planets.xml

<?xml version="1.0"?> <?xml-stylesheet type="text/xml" href="planets.xsl"?> <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>

Thats how to use the <?xml-stylesheet?> element; now its time to start working on writing the stylesheet itself. Ill do that by creating planets.xsl.

Категории