Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create XML from Perl?

Tags:

xml

perl

I need to create XML in Perl. From what I read, XML::LibXML is great for parsing and using XML that comes from somewhere else. Does anyone have any suggestions for an XML Writer? Is XML::Writer still maintained? Does anyone like/use it?

In addition to feature-completeness, I am interested an easy-to-use syntax, so please describe the syntax and any other reasons why you like that module in your answer.

Please respond with one suggestion per answer, and if someone has already answered with your favorite, please vote that answer up. Hopefully it will be easy to see what is most popular.

Thanks!

like image 316
pkaeding Avatar asked Sep 30 '08 20:09

pkaeding


People also ask

How do I create an XML file in Perl?

If you want to take a data structure in Perl and turn it into XML, XML::Simple will do the job nicely. At its simplest: my $hashref = { foo => 'bar', baz => [ 1, 2, 3 ] }; use XML::Simple; my $xml = XML::Simple::XMLout($hashref);


1 Answers

Just for the record, here's a snippet that uses XML::LibXML.

#!/usr/bin/env perl  # # Create a simple XML document #  use strict; use warnings; use XML::LibXML;  my $doc = XML::LibXML::Document->new('1.0', 'utf-8');  my $root = $doc->createElement('my-root-element'); $root->setAttribute('some-attr'=> 'some-value');  my %tags = (     color => 'blue',     metal => 'steel', );  for my $name (keys %tags) {     my $tag = $doc->createElement($name);     my $value = $tags{$name};     $tag->appendTextNode($value);     $root->appendChild($tag); }  $doc->setDocumentElement($root); print $doc->toString(); 

and this outputs:

<?xml version="1.0" encoding="utf-8"?> <my-root-element some-attr="some-value">     <color>blue</color>     <metal>steel</metal> </my-root-element> 
like image 93
Cosimo Avatar answered Sep 28 '22 03:09

Cosimo