Question

I'm having a hard time making a Perl script to correctly parse an XML file which looks like the following:

<Report name="NAME">
<ReportHost name="UNIQUE_1"><HostProperties>
<tag name="TAG_1">tag_value</tag>
<tag name="TAG_2">tag_value</tag>
</ReportHost>
<ReportHost name="UNIQUE_2"><HostProperties>
<tag name="TAG_1">tag_value</tag>
<tag name="TAG_2">tag_value</tag>
</ReportHost>

Now, I need to be able to call those UNIQUE_n somehow, but I couldn't manage. Dumper returns a structure like the following:

'Report' => {
            'ReportHost' => {
                             'UNIQUE_1' => {
                                           'HostProperties' => {
                                                               'tag' => { [...]

I tried ForceArray, but couldn't make ReportHost an array and failed miserably.

Was it helpful?

Solution

You say you're having trouble getting Perl to "correctly parse" the XML But you don't say what sort of result you want. Putting aside the fact that your example XML is missing some closing tags, perhaps you're wanting something like this:

my $report = XMLin(\*DATA,
    ForceArray => [ 'ReportHost', 'tag' ],
    KeyAttr    => { tag => 'name' },
    ContentKey => '-content',
);

print Dumper($report);

Which gives:

$VAR1 = {
      'ReportHost' => [
                      {
                        'HostProperties' => {
                                            'tag' => {
                                                     'TAG_1' => 'tag_value',
                                                     'TAG_2' => 'tag_value'
                                                   }
                                          },
                        'name' => 'UNIQUE_1'
                      },
                      {
                        'HostProperties' => {
                                            'tag' => {
                                                     'TAG_1' => 'tag_value',
                                                     'TAG_2' => 'tag_value'
                                                   }
                                          },
                        'name' => 'UNIQUE_2'
                      }
                    ],
      'name' => 'NAME'
};

And you could loop through the data like this:

my $report_hosts = $report->{ReportHost};
foreach my $report_host ( @$report_hosts ) {
    print "Report: $report_host->{name}\n";
    my $props = $report_host->{HostProperties}->{tag};
    print "  TAG_1: $props->{TAG_1}\n";
    print "  TAG_2: $props->{TAG_2}\n";
}

I would recommend using a different module though :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top