Re: Help with accessing an unknown set of data generated by XML::Simple
Francisco Obispo <[email protected]> Thu, 23 Feb 2012 15:52:58 -0800
| Newsgroups | gmane.comp.lang.perl.xml |
|---|---|
| Message-ID | <[email protected]> |
Hi Dale,
here are some comments:
On Feb 23, 2012, at 3:10 PM, Dale Puckett wrote:
> 1. I need to figure out how to be able to put out the XML in the same order contained in the Sample file as that is what the vendors expect.
If the vendor is expecting a custom-generated XML file, you should ask to see if they have an XML Schema, DTD, RELAX-NG, or other format specification on how they want it… If this is the case, you might end up writing one function to generate an XML, per vendor type.
> 2. I having trouble wrapping my head around a way to access each node and get its value when I do not know the name of the node. The example Francisco provided does a great job pulling out a list of known nodes that are presented in the @WANTED array, but I haven't figured out how to generalize it so that I get all of the nodes, their names and values when they exist.
XML::Simple is returning a reference to a hash, that is similar to the structure found in the XML document. You probably don't want to flatten up that structure, because you run the risk of loosing information.. consider the following:
<test>
<name>This is a test</name>
<project>
<name>Project Name #1</name>
</project>
</test>
if you move everything into a simple hash, you would only be able to store one 'name' key.. This is where the hash references come handy, XML::Simple will generate:
$ perl -MXML::Simple -MData::Dumper -e 'my $xml=XMLin("test.xml");print Data::Dumper->Dump([$xml])'
$VAR1 = {
'project' => {
'name' => 'Project Name #1'
},
'name' => 'This is a test'
};
which gives you the ability to:
$xml->{name} # This is a test
$xml->{project}->{name} # Project Name #1
$xml->{project} # HASH(0x7f8ccc19b3c8) -> hash reference
If you want to know "what's under project", you can get it like:
my @keys_under_project = keys %{ $xml->{project} }
The explanation is simple: 'keys' is expecting a HASH, not a HASHREF, so you need to de-reference the hash so it can be treated like a HASH, and to do that, you can use the %{} operator (more info: perl prefix dereferencing operators).
Note that if you print $xml->{project} you know you have a HASH reference because of HASH(<memory_address>) format.. the sane way to check for this is using the 'ref' function, which tells you if the scalar is a reference, and if so, to what.
more info: perldoc -f ref
Best regards,
Francisco Obispo
email: [email protected]
Phone: +1 650 423 1374 || INOC-DBA *3557* NOC
PGP KeyID = B38DB1BE
_______________________________________________
Perl-XML mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs