use XML::Simple;
use Data::Dumper;
my $ref = XMLin(\*DATA);
print Dumper $ref;
__DATA__
<?xml version="1.0" encoding="UTF-8"?>
<list>
<item>
<name>item_name_1</name>
<working>yes</working>
<uptime>5</uptime>
<downtime></downtime>
</item>
<item>
<name>item_name_2</name>
<working>yes</working>
<uptime>5</uptime>
<downtime></downtime>
</item>
</list>
And the results?
$VAR1 = {
'item' => {
'item_name_1' => {
'uptime' => '5',
'downtime' => {},
'working' => 'yes'
},
'item_name_2' => {
'uptime' => '5',
'downtime' => {},
'working' => 'yes'
}
}
};
So yes, if this is what you did then i can definitely see
how you would prematurely dismiss the module as the
"wrong answer". But, if you had RTFM'ed, you would have
seen that KeyAttr is taking the name
tags and making them hash keys to each row of XML data.
By simply changing the constructor's args to:
my $ref = XMLin(\*DATA,KeyAttr=>[]);
the results are now:
$VAR1 = {
'item' => [
{
'uptime' => '5',
'downtime' => {},
'working' => 'yes',
'name' => 'item_name_1'
},
{
'uptime' => '5',
'downtime' => {},
'working' => 'yes',
'name' => 'item_name_2'
}
]
};
And look how trivally easy it is to get the parts:
print $_->{name} for @{$ref->{item}};
"I needed more control of the output anyway."
What does that mean? Personally, i don't think you are
parsing XML, i think you are parsing something that
merely looks like XML. You asked the best way to
parse XML, we told you. You then added more requirements,
but i still say you are wasting time. Do me a favor, keep
track of how many hours you spend maintaining your 16 lines
of "parser" code (correcting mistakes, adding new features)
and compare that to the one hour it takes to install
XML::Simple and read the manual.
Now please don't get me wrong, i wish you success. I have
worked for shops that reinvent every wheel along the way
and they all suffer because of it. It is a foolish,
egotistical, and wasteful methodology. Listen to Maverick.
|