【问题标题】:What is the best way to write and read XML in perl?在 perl 中编写和读取 XML 的最佳方法是什么?
【发布时间】:2012-06-15 17:55:16
【问题描述】:

我正在使用 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;

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

【问题讨论】:

标签: xml perl perl-data-structures


【解决方案1】:

关于这些 CPAN 模块的情况:

  • XML::LibXML
  • XML::Writer
  • XML::简单

【讨论】:

  • 强调 XML::Simple。尽管有它的名字,但多年来我已经与那个特定的模块争论了很多 XML。
  • 获取 XML::Simple 以生成给定消费者将实际阅读的内容可能非常困难。我推荐 XML::Twig、XML::Writer、XML::LibXML
  • XML::Simple 与我在下面的回答相比,让我的生活轻松多了,谢谢:P
  • XML::Simple 的 cpan 页面说不鼓励使用该模块,人们应该改用 XML::LibXML。
【解决方案2】:

我应该更加努力地搜索,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>

感谢所有回答的人

【讨论】:

  • 那个比较奇怪。这不是真正的动态。如果你想要一个静态结构,你也可以考虑Text::Template。无论如何,请养成use strictuse warnings 的习惯。请。 :)
猜你喜欢
  • 1970-01-01
  • 2010-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-04
  • 1970-01-01
  • 2010-09-23
  • 1970-01-01
相关资源
最近更新 更多