导航:[首页]->[bash]->[perl使用XML::XPath读取xml]

###注意:此库已经长时间未更新,使用xml::libxml替代

##Install #!/bin/bash apt-get install libxml-xpath-perl

##XPath <table> 123 String Value 346 Text Value -23 stringValue </table>

#!/usr/bin/perl

use XML::XPath;
use XML::XPath::XMLParser;

my $xp = XML::XPath->new(filename=>"a.xml");

# 读取元素
my $nodeset = $xp->find("/xml/table/rec/numField");

foreach my $node ($nodeset->get_nodelist)
{
        print $node->getChildNode(1)->getValue() . "\n";
}

# 读取属性
my $nodeset = $xp->find("/xml/table/rec");

foreach my $node ($nodeset->get_nodelist)
{
        print $node->getAttribute ("id") . "\n";
}                                   

# 条件中包含属性
my $nodeset = $xp->find("/dir/d[attribute::n='b']");
foreach my $node ($nodeset->get_nodelist)
{
        print $node->getChildNode(1)->getValue() . "\n";
}

##参考

  1. http://search.cpan.org/~msergeant/XML-XPath-1.13/XPath.pm
  2. http://docstore.mik.ua/orelly/xml/pxml/ch08_02.htm