首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XML::解析器打印单个属性值

XML::解析器打印单个属性值
EN

Stack Overflow用户
提问于 2014-10-02 16:59:58
回答 1查看 157关注 0票数 1

我正在解析一个XML文件,该文件有类似的节点。

代码语言:javascript
复制
<product id="12345" model="dvd" section="cmp" img="junk.jpg"></product>

这是我的密码。我需要打印所有产品的id属性值。

代码语言:javascript
复制
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;
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-02 17:08:50

由于id%attrs哈希中有,所以只需打印它:

代码语言:javascript
复制
sub handle_start {
    my ( $expat, $element, %attrs ) = @_;
    if ( $element eq 'product' ) {
        print $attrs{id}, "\n";
    }
}

XML::Parser是一个低级的解析器.如果考虑使用更复杂的API,请尝试XML::树枝

代码语言:javascript
复制
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);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26165777

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档