我正在解析一个XML文件,该文件有类似的节点。
<product id="12345" model="dvd" section="cmp" img="junk.jpg"></product>这是我的密码。我需要打印所有产品的id属性值。
use XML::Parser;
my $parser = XML::Parser->new( Handlers => { Start => \&handle_start } );
$parser->parsefile('D:\Project\mob.xml');
sub handle_start {
my ( $expat, $element, %attrs ) = @_;
if ( $element eq 'product' ) {
print $element;
}
}发布于 2014-10-02 17:08:50
由于id在%attrs哈希中有,所以只需打印它:
sub handle_start {
my ( $expat, $element, %attrs ) = @_;
if ( $element eq 'product' ) {
print $attrs{id}, "\n";
}
}XML::Parser是一个低级的解析器.如果考虑使用更复杂的API,请尝试XML::树枝。
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);https://stackoverflow.com/questions/26165777
复制相似问题