Xml 解析器打印单个属性值
我正在解析一个XML文件,该文件有如下节点Xml 解析器打印单个属性值,xml,perl,xml-parsing,Xml,Perl,Xml Parsing,我正在解析一个XML文件,该文件有如下节点 <product id="12345" model="dvd" section="cmp" img="junk.jpg"></product> 由于在%attrs散列中有id,因此只需打印它: sub handle_start { my ( $expat, $element, %attrs ) = @_; if ( $element eq 'product' ) { print $attrs{i
<product id="12345" model="dvd" section="cmp" img="junk.jpg"></product>
由于在
%attrs
散列中有id
,因此只需打印它:
sub handle_start {
my ( $expat, $element, %attrs ) = @_;
if ( $element eq 'product' ) {
print $attrs{id}, "\n";
}
}
XML::Parser
是一个低级解析器。如果您考虑使用更复杂的API,请尝试:
使用警告;
严格使用;
使用XML::Twig;
my$xml={product=>sub{print$\->att('id'),“\n”},
);
$twig->parse($xml);
XML::LibXML:say$\->value for$doc->findnodes('//product/@id')代码>
sub handle_start {
my ( $expat, $element, %attrs ) = @_;
if ( $element eq 'product' ) {
print $attrs{id}, "\n";
}
}
use warnings;
use strict;
use XML::Twig;
my $xml = <<XML;
<product id="12345" model="dvd" section="cmp" img="junk.jpg"></product>
XML
my $twig = XML::Twig->new(
twig_handlers => { product => sub { print $_->att('id'), "\n" } },
);
$twig->parse($xml);