1

我正在使用 XML::Simple 并且我在变量 $xmldata 中有以下 XML 结构,我需要通过 Perl 代码访问它。

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

我可以使用以下代码访问 a 和 b 的值:

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

现在,我的问题是:我怎样才能得到 d2 的值?

4

1 回答 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.

于 2009-06-22T12:30:07.930 回答