How can I extract attributes from repeated tags in XML using Perl?
I am trying to parse a set of XML files. The XML file may have single flag tag or multiple flag tags:
<job> <flag exit="0">aaa</flag> </job>
OR
<job>
开发者_Go百科 <flag exit="0">aaa</flag>
<flag exit="1">bbb</flag>
<flag exit="2">ccc</flag>
</job>
But determining this "flag" count has to be determined on the fly. What's the best way to determine the flag count and print the values in it?
use XML::Simple;
use Data::Dumper;
# This reads the data after the __DATA__ pragma
# into an array, which is then joined with no spaces
# to build the string $xml
my $xml = join '', <DATA>;
# XMLin takes a filename, string or an IO::Handle object
# and slurps that data appropriately into a hash structure
my $config = XMLin($xml);
# Just look at the structure...
# print Dumper $config;
my $tag_count = @{$config->{flag}};
# As suggested in a comment below,
# an alternative is to force the structure to be array based
# even for single elements, with XMLin($xml, ForceArray => 1);
if ($tag_count > 1) {
print $_->{content}, q{ } for @{$config->{flag}}; # => aaa bbb ccc
print $_->{exit}, q{ } for @{$config->{flag}}; # => 0 1 2
}
else {
print $config->{flag}{content}; # => aaa
print $config->{flag}{exit}; # => 0
}
__DATA__
<job>
<flag exit="0">aaa</flag>
<flag exit="1">bbb</flag>
<flag exit="2">ccc</flag>
</job>
You can use XML::Simple's ForceArray
option to force every tags or some tags to be extracted in array.
精彩评论