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 ?

1
  • I have deleted my answer. You should mark newt's answer as the correct one because it resolves your issue. Commented Jun 22, 2009 at 20:13

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@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.
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, yes you are absolutely right. My mistake. Corrected the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.