in reply to 3Re: Parsing XML into a Hash
in thread Parsing XML into a Hash

Clueless?
No, not really. This is a secure site, and they take this very seriously. Besides, after further consideration of the entire thing, it was determined that XML::Simple just wasn't the right answer. I needed more control of the output anyway. Besides, the resulting code is only about 16 lines, including for proper spacing of the code and all. So, things work out in the end after all.

Replies are listed 'Best First'.
5Re: Parsing XML into a Hash
by jeffa (Bishop) on Nov 07, 2003 at 13:38 UTC

    "...it was determined that XML::Simple just wasn't the right answer."

    Well, sometimes XML::Simple is not enough, but in this case i think you didn't spend enough time in research. Here is how i imagine you tested out XML::Simple:
    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.

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)