Perl Programming Page 3 - XSL Transformations with Perl, Revisited |
This next example demonstrates the capabilities of the XML::XSLT processor more than its functionality. Consider the XML file that I've used in the examples thus far: <?xml version="1.0"?> Let's assume that, for some quirky reason, I want to prepare a list of stocks in my portfolio. The output XML should look like this: <stocks> While I can load the XML file in a DOM object and retrieve specific nodes (and/or attributes) of interest, the exercise -- take my word for it -- will soon spiral into a complex and unmanageable piece of code. Instead, I'll show you how to use XSLT to create a new XML structure from an existing one without much sweat. Fortunately, the XML::XSLT processor has support for the XSLT elements (to create XML elements and attributes) to get the job done. First, here is the XSL style sheet that brings about the transformation: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> A quick word about the XSLT style sheet listed above: note the use of the <xslt:element> XSLT element to define a custom <stocks> element. Next, I've used the <xsl:for-each> construct to iterate over the <stock> elements (in the original XML file) and created the <symbol> and <companyname> elements for each stock in my portfolio. # /usr/bin/perl # import required modules # define local variables # create an instance of XSL::XSLT processor # some more error handling here ... # transform the XML DOM object using the XSL style sheet # ... here ... # output new XML to file # ... and finally, here. # free up memory Above, I've listed the Perl script that carries out the required transformation. You should notice one minor difference between this example and all other examples that I've demonstrated, thus far. Can you spot it? If you drilled straight down to the following code snippet, then pat yourself on the back! // snip # transform the XML DOM object using the XSL style sheet # ... here ... # output new XML to file // snip Here, you'll see that I've stored the output of the transformation in a DOM object instead of sending it to the output screen. Of course, I'll need to store the XML data to file eventually. This is where the printToFile() method of the XML::DOM module comes in handy. I pass the name of the output file to this printToFile()method and XML::DOM module will create a file with the required XML output.
blog comments powered by Disqus |
|
|
|
|
|
|
|