tags:

views:

145

answers:

2

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>
  <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?

+2  A: 
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>
Pedro Silva
i dont want to print the count but the values in it.... the first case should print aaa and the next case should print aaa,bbb,ccc. is it possible to do that in a single line of code? i.e depending on whether its single or array of flags, i wanted to print the values....
siva
Just use Data::Dumper to look at the structure, perhaps that will help you understand how XML::Simple structures the data.
Pedro Silva
hi Pedro Silva, what is the use of join statement... can u pls tell me how do i do that if the files are stored as xml say a.xml... in that case, how the join stmt should be modified
siva
this code works only for array of tags... not single tag
siva
See http://search.cpan.org/perldoc?XML::Simple#ForceArray_=%3E_1_#_in_-_important
David Dorward
Good god man, just check the number of elements in @{$config->{flag}}. Updated the post.
Pedro Silva
+1  A: 

You can use XML::Simple's ForceArray option to force every tags or some tags to be extracted in array.

sebthebert