Tudor Constantin
Tudor Constantin

Reputation: 26861

Add a reference to an XSLT in Perl using only XML:LibXML

I have a XML created dynamically. However, I want to add a reference to an XSLT file in it, to be able to render the XML file as HTML in Mozilla.

I want my final XML to start something like this:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="xslt_stylesheet_file.xsl"?>
<root_node>
</root_node>

I am not able to install XML::LibXSLT, so that is not a solution. Another solution would be to write the XML in a file, open it as a regular file and add the XSLT reference to it - but that just doesn't seem right to me.

Are there elegant solutions to this?

Edit:

Added some code

use strict;
use warnings;
use XML::LibXML;

my $final_xml = XML::LibXML::Document->new('1.0','utf-8');

 my $root_node = $final_xml->createElement('root'); 

 $final_xml->setDocumentElement( $root_node );


open (MYFILE, '>final.xml' );
 print MYFILE $final_xml->toString();
close (MYFILE);

And the output is:

<?xml version="1.0" encoding="utf-8"?>
<root/>

Upvotes: 4

Views: 703

Answers (2)

mzjn
mzjn

Reputation: 50947

use strict;
use warnings;
use XML::LibXML;

my $final_xml = XML::LibXML::Document->new('1.0','utf-8');

my $pi = $final_xml->createProcessingInstruction("xml-stylesheet");
$pi->setData(type=>'text/xsl', href=>'xslt_stylesheet_file.xsl');
$final_xml->appendChild($pi);

my $root_node = $final_xml->createElement('root'); 
$final_xml->setDocumentElement($root_node);

$final_xml->toFile("final.xml")

=>

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet href="xslt_stylesheet_file.xsl" type="text/xsl"?>
<root/>

Upvotes: 5

Stuart Watt
Stuart Watt

Reputation: 5391

If you only want to generate XML, I'd use XML::Writer. then you can use the xmlDecl method to add your declaration. It's a more SAX-like API than XML::LibXML, but usually when generating documents that is not as much of an issue as when processing them. Also XML::Writer doesn't depend on the libxml2 and libxslt, so it is much easier to install.

Upvotes: 1

Related Questions