I need to render a node set found via XML::XPath
my $source = XML::LibXML->load_xml(location => 'xml/animals.xml');
my $nodeset = $source->find('//area[@id="01"]');
using an XSLT template with XML::LibXSLT:
my $xslt = XML::LibXSLT->new();
my $style_doc = XML::LibXML->load_xml(location=>'xml/animal_template.xsl', no_cdata=>1);
my $stylesheet = $xslt->parse_stylesheet($style_doc);
but I can’t simply give the nodeset to the $stylesheet->transform():
my $results = $stylesheet->transform($nodeset);
because transform is expecting a XML::LibXML::Document object, not XML::XPath::NodeSet.
What should I do? Is there a way to create an XML::LibXML::Document from a XML::XPath::NodeSet?
Or maybe to give the XSLT template a variable so I don’t have to find the nodes with XPath?
There is no direct method to convert an
XML::XPath::NodeSetobject to anXML::LibXML::Documentobject. Furthermore it isn’t possible in general as a Nodeset can contain any number of XML elements while an XML document must have exactly one root element.But XPath is an integral part of XSLT, so there is no reason why you shouldn’t rewrite the transform so that it does the selection
//area[@id="01"]itself, and then supply it the entire document, as parsed by XML::LibXML. This is the method I would choose.If you have reasons to select the
<area id="01">elements separately then it would be possible to build a new XML document by converting each element in the Nodeset to a string and bundling them into a dummy<root>XML element, but that is far from an ideal solution.If you have questions about implementing a solution then please ask again.