我有一些XML,看起來像這樣:使用XML :: Twig,有沒有找到具有特定屬性的'first_child'的方法?
<?xml version="1.0" encoding="UTF-8"?>
<DataSet>
<Category>
<Name mode="source">somename</Name>
<Name mode="destination">someothername</Name>
<Content>Some text here</Content>
</Category>
</DataSet>
我試圖做的是過程中的「類別」,並提取基於上下文不同的名稱。
我試着children
迭代它 - 這個工程:
use strict;
use warnings;
use XML::Twig;
sub process_category {
my ($twig, $category) = @_;
my $cat_name;
foreach my $name ($category->children('Name')) {
if ($name->att('mode') eq 'source') {
$cat_name = $name->text;
}
}
print "$cat_name ", $category->first_child_text('Content'), "\n";
}
my $twig =
XML::Twig->new(twig_handlers => { 'Category' => \&process_category })
->parse(\*DATA);
__DATA__
<?xml version="1.0" encoding="UTF-8"?>
<DataSet>
<Category>
<Name mode="source">somename</Name>
<Name mode="destination">someothername</Name>
<Content>Some Text</Content>
</Category>
</DataSet>
但是我想知道 - 有超過迭代的元素更好的辦法?我無法弄清楚first_child
是否支持屬性搜索,或者是否有另一種方法。
可愛,這聽起來甚至比我在看的代碼ref解決方案更好。 – Sobrique