如何使用XMLParser获取item-> @url,item-> @replace和item->“value inside” 将内容作为节点的字符串,其中item-> @ cone =“one”?
<cstep>
<item cone="one"
url="http://google.com/{ccc}/cthree"
replace="{ccc}">
<itemsub conesub="conesub">
<itemsubsub conesubsub="conesubsub" />
</itemsub>
</item>
<item cone="two"
url="http://google.com/{ccc}/cthree"
replace="{ccc}">
<itemsub conesub="conesub">
<itemsubsub conesubsub="conesubsub" />
</itemsub>
</item>
</cstep>
答案 0 :(得分:3)
use warnings;
use strict;
use XML::Twig;
my $str = <<EOF;
<cstep>
<item cone="one"
url="http://google.com/{ccc}/cthree"
replace="{ccc}">
<itemsub conesub="conesub">
<itemsubsub conesubsub="conesubsub" />
</itemsub>
</item>
<item cone="two"
url="http://google.com/{ccc}/cthree"
replace="{ccc}">
<itemsub conesub="conesub">
<itemsubsub conesubsub="conesubsub" />
</itemsub>
</item>
</cstep>
EOF
my $t = XML::Twig->new(twig_handlers => {'cstep/item' => \&item });
$t->parse($str);
sub item {
my ($t, $item) = @_;
if ($item->att('cone') eq 'one') {
print $item->att('url' ), "\n";
print $item->att('replace'), "\n";
}
}
__END__
http://google.com/{ccc}/cthree
{ccc}
更新:要回答有关在子资源外指定$url
的评论中的问题:
my $t = XML::Twig->new(twig_handlers => {'cstep/item' => \&item });
my $url;
$t->parse($str);
print "$url\n";
sub item {
my ($t, $item) = @_;
if ($item->att('cone') eq 'one') {
$url = $item->att('url');
print $item->att('replace'), "\n";
}
}