在perl中编写和读取XML的最佳方法是什么?

时间:2012-06-14 20:35:55

标签: xml perl perl-data-structures

我正在使用Perl程序,只需使用打开,打印,关闭的典型函数就可以写入XML文件。 XML文件稍后会被PHP Web应用程序消化。

#!/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;

这或多或少基本上是当前系统的工作方式。我相信一定有更好的方法。

2 个答案:

答案 0 :(得分:6)

这些CPAN模块是什么:

  • XML ::的libxml
  • XML ::作家
  • XML ::简单

答案 1 :(得分:1)

我应该更努力地搜索,Found the XML::Writer Here

从这里提出的问题:How can I create XML from Perl?‌​

Sebastian Stumpf引起了我的注意,

语法如下

 #!/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(  );

产地:

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

谢谢所有回答

的人