Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Xml 解析器打印单个属性值_Xml_Perl_Xml Parsing - Fatal编程技术网

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

我正在解析一个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{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);