Home > Articles > Programming > Java

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

This chapter is from the book

Applying Style Sheets Dynamically

Inserting an <?xml-stylesheet> directive in an XML document is not the only way to associate a style sheet with that document. As you'll see in Chapters 9, 10, and 11, you can also use programming techniques to attach the style sheet on the fly. The basic technique is to use the Document Object Model's transformNode() method. The method takes the name of a style sheet as a parameter and assigns it to the document object you've specified.

As an example, you could take the XML document in Listing 2.1, remove the <?xml-stylesheet> directive, and place the document on a Web server. You would also place the XSLT style sheet containing the HTML transformation in the same directory on the server. Then, you could use a script that transforms the XML document and sends the HTML transformation to a requesting browser. The script would simply write something like this:

xmlObject = transformNode(xslObject)

The script could take the result stored in xmlObject and stream it back to the browser. In this case, what gets streamed back is Listing 2.4. When it hits the browser, the browser renders the HTML and displays the screen shown in Figure 2.3.

  • + Share This
  • 🔖 Save To Your Account