0

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.

daxim
  • 39,270
  • 4
  • 65
  • 132
Beau Bouchard
  • 835
  • 11
  • 28

2 Answers2

6

What's about these CPAN modules:

  • XML::LibXML
  • XML::Writer
  • XML::Simple
Pavel Vlasov
  • 3,455
  • 21
  • 21
  • Emphasis on XML::Simple. Despite it's name, I've wrangled a lot of XML over the years with that particular module. – David Jun 14 '12 at 23:16
  • 3
    Getting XML::Simple to generate something that a given consumer will actually read can be *very* hard. I recommend XML::Twig, XML::Writer, XML::LibXML – hobbs Jun 15 '12 at 00:26
  • XML::Simple made my life so much easier compared to my answer below, thank you :P – Beau Bouchard Jun 15 '12 at 15:37
  • The cpan page for XML::Simple says use of the module is discouraged, and that people should use XML::LibXML instead. – Michael Younkin Oct 25 '12 at 04:43
1

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

Community
  • 1
  • 1
Beau Bouchard
  • 835
  • 11
  • 28
  • 1
    That one is rather strange. It's not really dynamic. If you want a static structure, you could also consider [Text::Template](http://search.cpan.org/~mjd/Text-Template-1.45/lib/Text/Template.pm). Regardless, **please make it a habit** to `use strict` and `use warnings`. Please. :) – simbabque Jun 14 '12 at 20:57