Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Creating a hash out of multiple XML attributes in an elment

by perlvroom (Acolyte)
on Jul 14, 2013 at 19:20 UTC ( #1044233=perlquestion: print w/ replies, xml ) Need Help??
perlvroom has asked for the wisdom of the Perl Monks concerning the following question:

Ok, the following script does what i need, but i was hoping someone could school me on how to do this more effeciently:
use XML::Twig; my $t= XML::Twig->new( twig_handlers => { 'settings' => \&file, } ) ->parsefile( 'sample.xml'); sub file{ my($t, $settings)=@_; foreach($settings->att('key')){ if($settings->att('key') eq 'a'){ $a = $settings->att('value'); } if($settings->att('key') eq 'b'){ $b = $settings->att('value'); } } }
XML snippet:
<settings key="a" value="1"/>
<settings key="b" value="2"/>
The goal is to declare the "key" attribute as a variable with it's value equal to the "value" attribute in the same element, for all "settings" elements.

Comment on Creating a hash out of multiple XML attributes in an elment
Download Code
Re: Creating a hash out of multiple XML attributes in an elment
by mirod (Canon) on Jul 14, 2013 at 19:34 UTC

    I think you want something like this:

    my $key2value; my $t= XML::Twig->new( twig_handlers => { 'settings' => sub { file( +@_, $key2value); } } ) ->parsefile( 'sample.xml'); sub file{ my($t, $settings, $key2value)=@_; $key2value->{$settings->att( 'key')}= $settings->att( 'value'); }
      Yep. This is going to be a stupid question but how do i retrieve/print the value for, say, key "a"?

        mirod used a key called "key", if you want a key called "a", maybe you should replace "key" with "a" or something like that, I haven't read perlintro so I'm not sure

        $key2value is a hash reference, you retrieve the value for a this way: $key2value->{a}

        see perldata for more info.

Re: Creating a hash out of multiple XML attributes in an elment
by Jenda (Abbot) on Jul 15, 2013 at 15:20 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1044233]
Approved by Happy-the-monk
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2015-07-04 21:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (60 votes), past polls