Beau Bouchard
Beau Bouchard

Reputation: 827

What is the best way to write and read XML in perl?

I am working with Perl programs that write to an XML file by just using the typical functions open, print, close. The XML files are later digested by a PHP Web application.

#!/usr/bin/perl
#opening file
open FILE, ">derp.xml" or die $!;

#data is created in variables like so...
$first       = '<\?xml version=\"1.0\" encoding=\"UTF-8\" \?>';
$openperson  = '<person>\n';
$name        = '<name>Gary</name>\n';
$birthday    = '<brithday>01/10/1999</birthday>\n';
$car         = '<car>minivan</car>\n';
$closeperson = '</person>\n';

#writing variables to file
print FILE $first;
print FILE $openperson;
print FILE $name;
print FILE $birthday;
print FILE $car;
print FILE $closeperson;
close FILE;

More or less this is basically how the current system works. I am sure there must be a better way.

Upvotes: 0

Views: 1352

Answers (2)

Beau Bouchard
Beau Bouchard

Reputation: 827

I should have searched harder, Found the XML::Writer Here

From this questions here: How can I create XML from Perl?‌​

That Sebastian Stumpf brought to my attention,

Syntax is as follows

 #!/usr/bin/perl

 use IO;
 my $output = new IO::File(">derp.xml");

 use XML::Writer;
 my $writer = new XML::Writer( OUTPUT => $output );

 $writer->xmlDecl( 'UTF-8' );
 $writer->startTag( 'person' );
 $writer->startTag( 'name' );
 $writer->characters( "Gary" );
 $writer->endTag(  );
 $writer->startTag( 'birthday' );
 $writer->characters( "01/10/1909" );
 $writer->endTag(  );
 $writer->startTag( 'car' );
 $writer->characters( "minivan" );
 $writer->endTag(  );
 $writer->endTag(  );
 $writer->end(  );

Produces:

  <?xml version="1.0" encoding="UTF-8"?>
  <person>
      <name>Gary</name>
      <birthday>01/10/1909</birthday>
      <car>minivan</car>
  <person>

Thank you all who answered

Upvotes: 1

Pavel Vlasov
Pavel Vlasov

Reputation: 3465

What's about these CPAN modules:

  • XML::LibXML
  • XML::Writer
  • XML::Simple

Upvotes: 6

Related Questions