使用Perl模块XML :: LibXML迭代XML数据

时间:2014-05-15 09:32:16

标签: xml perl libxml2 xmldom

有人可以将此翻译(XML::DOM改为XML::LibXML)吗?

我已经使用了几个小时,所以我不会把我尝试过的所有代码都填满,因为它会填充页面

foreach my $review ($review_details->getElementsByTagName("review")) { # find the node review{

  # scroll through each review to get the details that we want

  foreach my $details ($review->getChildNodes) {

    if ($details->getNodeName eq "movie_title") {
      foreach my $movie_title ($details->getChildNodes) {
        print $movie_title->getNodeValue . "\n";
      }
    }

    if ($details->getNodeName eq "reviewer") {
      foreach my $reviewer ($details->getChildNodes) {
        print $reviewer->getNodeValue . "\n";
      }
    }

  }
}

这是数据的基本表示

<results>
  <review>
    <movie_title>First Movie</movie_title>
    <reviewer>Annie</reviewer>
  </review>
  <review>
    <movie_title>Second Movie</movie_title>
    <reviewer>Bob</reviewer>
  </review>
  <review>
    <movie_title>Third Movie</movie_title>
    <reviewer>Charlie</reviewer>
  </review>
  <review>
    <movie_title>Fourth Movie</movie_title>
    <reviewer>Don</reviewer>
  </review>
</results>

我尝试使用XML::LibXML的一些内容涉及不同版本的行,例如

foreach my $review ($review_details>findnodes('//display_name')) { 
  print $review->findvalue('movie_title')
}

2 个答案:

答案 0 :(得分:2)

如果您使用XPath表达式并遍历所有review元素,这非常简单。

use strict;
use warnings;

use XML::LibXML;

my $doc = XML::LibXML->load_xml(IO => *DATA);

for my $review ( $doc->findnodes('/results/review') ) {
  print $review->findvalue('movie_title'), "\n";
  print $review->findvalue('reviewer'), "\n";
}

__DATA__
<results>
  <review>
    <movie_title>First Movie</movie_title>
    <reviewer>Annie</reviewer>
  </review>
  <review>
    <movie_title>Second Movie</movie_title>
    <reviewer>Bob</reviewer>
  </review>
  <review>
    <movie_title>Third Movie</movie_title>
    <reviewer>Charlie</reviewer>
  </review>
  <review>
    <movie_title>Fourth Movie</movie_title>
    <reviewer>Don</reviewer>
  </review>
</results>

<强>输出

First Movie
Annie
Second Movie
Bob
Third Movie
Charlie
Fourth Movie
Don

答案 1 :(得分:1)

我可能不会在XML :: LibXML中使用这么多循环:

#!/usr/bin/perl
use warnings;
use strict;

use XML::LibXML;

my $review_details = 'XML::LibXML'->load_xml( location => shift );

for my $review ($review_details->findnodes('/results/review')) {
    print $review->findvalue($_), "\n" for 'movie_title', 'reviewer';
}

或者,我使用XML::XSH2,XML :: LibXML的包装器:

open file.xml ;
for /results/review echo :s (movie_title) {"\n"} (reviewer) ;