Template::Plugin::XML::LibXML - XML::LibXML Template Toolkit Plugin
[% USE docroot = XML.LibXML("helloworld.xml") %] The message is: [% docroot.find("/greeting/text") %]
This module provides a plugin for the XML::LibXML module. It can be utilised the same as any other Template Toolkit plugin, by using a USE statement from within a Template. The use statment will return a reference to root node of the parsed document
The plugin is capable of using either a string, a filename or a filehandle as a source for either XML data, or HTML data which will be converted to XHTML internally.
The USE statement can take one or more arguments to specify what XML should be processed. If only one argument is passed then the plugin will attempt to guess how what it has been passed should be interpreted.
When it is forced to guess what type of data it is used the routine will first look for an open filehandle, which if it finds it will assume it's a filehandle to a file containing XML. Failing this (in decreasing order) it will look for the chars "<?xml" at the start of what it was passed (and assume it's an XML string,) look for a "<html>" tag (and assume it's HTML string,) look for a "<" (and assume it's XML string without a header,) or assume what it's been passed is the filename to a file containing XML.
In the interests of being explicit, you may specify the type of data you are loading using the same names as in the XML::LibXML documentation:
# value contains the xml string [% USE docroot = XML.LibXML(string => value) %] # value contains the filename of the xml [% USE docroot = XML.LibXML(file => value) %] # value contains an open filehandle to some xml [% USE docroot = XML.LibXML(fh => value) %] # value contains the html string [% USE docroot = XML.LibXML(html_string => value) %] # value contains the filename of the html [% USE docroot = XML.LibXML(html_file => value) %] # value contains an open filehandle to some html [% USE docroot = XML.LibXML(html_fh => value) %]
Or, if you want you can use similar names to that the XML.XPath plugin uses:
# value contains the xml string [% USE docroot = XML.LibXML(xml => value) %] or [% USE docroot = XML.LibXML(text => value) %] # value contains the filename of the xml [% USE docroot = XML.LibXML(filename => value) %] # value contains the html string [% USE docroot = XML.LibXML(html => value) %] or [% USE docroot = XML.LibXML(html_text => value) %] # value contains the filename of the html [% USE docroot = XML.LibXML(html_file => value) %] [% USE docroot = XML.LibXML(html_filename => value) %]
You can provide extra arguments which will be used to set parser options. See XML::LibXML for details on these. I will repeat the following warning however: "LibXML options are global (unfortunately this is a limitation of the underlying implementation, not this interface)...Note that even two forked processes will share some of the same options, so be careful out there!"
# turn off expanding entities [% USE docroot = XML.LibXML("file.xml", expand_entities => 0);
XML::LibXML provides two simple mechanisms for obtaining sections of the XML document, both of which can be used from within the Template Toolkit
The first of these is to use a XPath statement. Simple values can be found with the
# get the title attribute of the first page node # (note xpath starts counting from one not zero) [% docroot.findvalue("/website/section/page/@title"); %] # get the text contained within a node [% htmldoc.findvalue("/html/body/h1/text()") %]
Nodes of the xml document can be found with the
# get all the pages ('pages' is a list of nodes) [% pages = docroot.findnodes("/website/section/page") %] # get the first page (as TT folds single elements arrays # to scalars, 'page1' is the one node that matched) [% page1 = docroot.findnodes("/website/section/page") %]
Then further xpath commands can then be applied to those nodes in turn:
# get the title attribute of the first page [% page1.findvalue("@title") %]
An alternative approach is to use individual method calls to move around the tree. So the above could be written:
# get the text of the h1 node [% htmlroot.documentElement .getElementsByLocalName("body").first .getElementsByLocalName("h1").first .textContent %] # get the title of the first page [% docroot.documentElement .getElementsByLocalName("section").first .getElementsByLocalName("page").first .getAttribute("title") %]
You should use the technique that makes the most since in the particular situation. These approaches can even be mixed:
# get the first page title [% page1 = htmlroot.findnodes("/website/section/page"); page1.getAttribute("title") %]
Much more information can be found in XML::LibXML::Node.
The simplest way to use this plugin is simply to extract each value you want to print by hand
The title of the first page is '[% docroot.findvalue("/website/section/page/@title") %]'
The title of the first page is '[% docroot.documentElement .getElementsByLocalName("section").first .getElementsByLocalName("page").first .getAttribute("title") %]'
You might want to discard whitespace from text areas. XPath can remove all leading and following whitespace, and condense all multiple spaces in the text to single spaces.
<p>[% htmlroot.findvalue("normalize-space( /html/body/p/text() )" | html %]</p>
Note that, as above, when we're inserting the values extracted into a XML or HTML document we have to be careful to re-encode the attributes we need to escape with something like the html filter. A slightly more advanced technique is to extract a whole node and use the toString method call on it to convert it to a string of XML. This is most useful when you are extracting an existing chunk of XML en mass, as things like <b> and <i> tags will be passed thought correctly and entities will be encoded suitably (for example '"' will be turned into '"')
# get the second paragraph and insert it here as XML [% htmlroot.findnodes("/html/body/p").toString %]
The most powerful technique is to use a view (as defined by the VIEW keyword) to recursively render out the XML. By loading this plugin
present methods will be created in the XML::LibXML::Node classes and subclasses. Calling
present on a node with a VIEW will cause it to be rendered by the view block matching the local name of that node (with any non alphanumeric charecters turned to underscores. So a <author> tag will be rendered by the 'author' block. Text nodes will call the 'text' block with the text of the node.
As the blocks can refer back to both the node it was called with and the view they can choose to recursively render out it's children using the view again. To better facilitate this technique the extra methods
starttag (recreate a string of the starting tag, including attributes,)
endtag (recreate a string of the ending tag) and
content (when called with a view, will render by calling all the children of that node in turn with that view) have been added.
This is probably best shown with a well commented example:
# create the view [% VIEW myview notfound => 'passthru' %] # default tag that will recreate the tag 'as is' meaning # that unknown tags will 'passed though' by the view [% BLOCK passthru; item.starttag; item.content(view); item.endtag; END %] # convert all sections to headed paragraphs [% BLOCK section %] <h2>[% item.getAttribute("title") %]</h2> <p>[% item.content(view) %]</p> [% END %] # urls link to themselves [% BLOCK url %] <a href="[% item.content(view) %]">[% item.content(view) %]</a> [% END %] # email link to themselves with mailtos [% BLOCK email %] <a href="mailto:[% item.content(view) %]">[% item.content(view) %]</a> [% END %] # make pod links bold [% BLOCK pod %] <b>[% item.content(view) %]</b> [% END %] # render text, re-encoding the attributes as we go [% BLOCK text; item | html; END %] # render arrays out [% BLOCK list; FOREACH i = item; view.print(i); END ; END %] [% END %] # use it to render the paragraphs [% USE doc = XML.LibXML("mydoc.xml") %] <html> <head> <title>[% doc.findvalue("/doc/page/@title") %]</title> </head> <body> [% sections = doc.findnodes("/doc/page/section"); FOREACH section = sections %] <!-- next section --> [% section.present(myview); END %] </body> </html>
In order to detect if a scalar is an open filehandle (which is used if the USE isn't explicit about it's data source) this plugin uses the
openhandle routine from Scalar::Util. If you do not have Scalar::Util installed, or the version of Scalar::Util is sufficiently old that it does not support the
openhandle routine then a much cruder
defined(fileno $scalar) check will be employed.
Bugs may be reported either via the CPAN RT at http://rt.cpan.org/NoAuth/Bugs.html?Dist=Template-Plugin-XML-LibXML or via the Template Toolkit mailing list: http://www.template-toolkit.org/mailman/listinfo/templates or direct to the author
Written by Mark Fowler <email@example.com>
Copyright Mark Fowler 2002-3, all rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This module wouldn't have been possible without the wonderful work that has been put into the libxml library by the gnome team or the equally wonderful work put in by Matt Sergeant and Christian Glahn in creating XML::LibXML.
On a similar note, you may want to see Template::Plugin::XML::XPath.
The t/test directory in the Template-Plugin-XML-LibXML distribution contains all the example XML files discussed in this documentation.