views:

180

answers:

1

I am using XML::Simple and I have the following XML structure in a variable $xmldata which I need to access through Perl code.

<root>
    <a>sfghs</a>
    <b>agaga</b>
    <c>
       <c1>sgsfs</c1>
       <c2>sgsrsh</c2>
    </c>
    <d>
        <d1>agaga</d1>
        <d2>asgsg</d2>
    </d>
</root>

I can access the value of a and b by using the following code :

$aval = $xmldata->{a}[0];
$bval = $xmldata->{b}[0] ;

Now, my question is: how can I get the value of say, d2 ?

+5  A: 

Given what you have above, I assume that you have the ForceArray flag enabled. Nested keys are stored as hashes of hashes using references.

So, to access 'd2' you would need to use:

my $d2val = $xmldata->{d}[0]->{d2}[0];

(or my preference)

my $d2val = $xmldata->{d}->[0]->{d2}->[0];

(because it makes the deref obvious)

Obviously, the deeper you go the scarier this gets. That's one of the reasons I almost always suggest XML::LibXML and XPath instead of XML::Simple. XML::Simple rapidly becomes not simple. XML::Simple docs explain how various options can affect this layout.

Data::Dumper is invaluable when you want to take a look at how the data are laid out.

Nic Gibson
@newt FYI: I deleted my answer and put the ref to Data::Dumper here so that there is one complete answer that can be marked as correct.
Sinan Ünür
Shouldn't that be my $d2val = $xmldata->{'d'}[0]{'d2'}[0];? (The difference being in the [0] after {'d'}, still asuming ForceArray => 1.) For larger documents I like XML::Parser::PerlSAX (whatever you do, once your documents get big don't DOM-parse them).
Anon
@Anon, yes you are absolutely right. My mistake. Corrected the answer
Nic Gibson
@Sinan - thanks :)
Nic Gibson