【问题标题】:XML reading using Perl使用 Perl 读取 XML
【发布时间】:2013-06-07 10:55:50
【问题描述】:

我是 Perl 语言的新手。我有一个类似的 XML,

<xml>
   <date>
       <date1>2012-10-22</date1>
       <date2>2012-10-23</date2>
   </date>
</xml>

我想解析这个 XML 文件并将其存储在数组中。如何使用 perl 脚本做到这一点?

【问题讨论】:

标签: perl xml-parsing


【解决方案1】:
Use XML::Simple - Easy API to maintain XML (esp config files) or 
see XML::Twig - A perl module for processing huge XML documents in tree mode.

例如:

use strict;
use warnings;
use XML::Simple;
use Data::Dumper;

my $xml = q~<xml>
   <date>
       <date1>2012-10-22</date1>
       <date2>2012-10-23</date2>
   </date>
</xml>~;

print $xml,$/;

my $data = XMLin($xml);

print Dumper( $data );

my @dates;
foreach my $attributes (keys %{$data->{date}}){
  push(@dates, $data->{date}{$attributes})
}

print Dumper(\@dates);

输出:

$VAR1 = [
          '2012-10-23',
          '2012-10-22'
        ];

【讨论】:

    【解决方案2】:

    这是XML::LibXML的一种方法

    #!/usr/bin/env perl
    use strict;
    use warnings;
    use XML::LibXML;
    
    my $doc = XML::LibXML->load_xml(location => 'data.xml');
    my @nodes = $doc->findnodes('/xml/date/*');
    my @dates = map { $_->textContent } @nodes;
    

    【讨论】:

      【解决方案3】:

      使用XML::XSH2,对XML::LibXML 进行包装:

      #!/usr/bin/perl
      use warnings;
      use strict;
      
      use XML::XSH2;
      
      xsh << '__XSH__';
        open 2.xml ;
        for $t in /xml/date/* { 
            my $s = string($t) ;
            perl { push @l, $s }
        }
      __XSH__
      
      no warnings qw(once);
      print join(' ', @XML::XSH2::Map::l), ".\n";
      

      【讨论】:

        【解决方案4】:

        如果您不能/不想使用任何 CPAN 模组:

        my @hits= $xml=~/<date\d+>(.+?)<\/date\d+>/
        

        这应该会为您提供 @hits 数组中的所有日期。

        如果 XML 不像您的示例那么简单,建议使用 XML 解析器,XML::Parser 就是其中之一。

        【讨论】:

        • 永远不要使用正则表达式来解析 xml
        • 好吧,假设您可以使用其他工具,但我发现自己在无法使用它们的非常旧的服务器上工作,所以如果 XML 足够简单,使用正则表达式并不漂亮但可以工作.
        • 如果您可以运行自己编写的 Perl 代码,则可以使用 Pure Perl XML 库。
        猜你喜欢
        • 1970-01-01
        • 2014-09-07
        • 2012-08-23
        • 1970-01-01
        • 2020-06-15
        • 1970-01-01
        • 1970-01-01
        • 2011-07-01
        • 1970-01-01
        相关资源
        最近更新 更多