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

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

Install

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

XPath

<xml>
<table>
<rec id="1">
<numField>123</numField>
<stringField>String Value</stringField>
</rec>
<rec id="2">
<numField>346</numField>
<stringField>Text Value</stringField>
</rec>
<rec id="3">
<numField>-23</numField>
<stringField>stringValue</stringField>
</rec>
</table>
</xml>

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