XPathによる名前空間付きの値の取得
XML::LibXMLモジュールを使うとXPathでノードを指定して値を取得できます。
名前空間はXML::LibXML::XPathContextモジュールのregisterNsで指定します。
use strict;
use warnings;
use XML::LibXML;
my $file = 'data.xml';
my $ns = 'http://example.com/config';
my $xpath = '/ns:configuration/ns:appSettings/ns:add';
binmode STDOUT, ":encoding(cp932)"; # Windows向け
my $doc = XML::LibXML->load_xml(location => $file);
my $xc = XML::LibXML::XPathContext->new($doc);
$xc->registerNs('ns', $ns);
my @nodes = $xc->findnodes($xpath);
foreach my $node (@nodes) {
my $key = $node->getAttribute('key');
my $value = $node->getAttribute('value');
printf "%s=%s\n", $key, $value;
}
__END__
上記のスクリプトはこんなXMLを対象としています。
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns="http://example.com/config">
<appSettings>
<add key="key1" value="値1" />
<add key="key2" value="値2" />
<add key="key3" value="値3" />
</appSettings>
</configuration>
