XML, the Perl Way




  perl wtr2_simple


the XML::Simple manpage is extremely convenient for loading XML data into a Perl data structure, using XMLin, and then forgetting that it was ever in XML.

The code was very easy to write. I used YAML during the debugging phase to dump the content of the $xml structure, so it was really easy to see where was the data I needed.

Note the 2 options for XMLin:

forcearray => [ qw(InvoiceRow)]
this will cause XMLin to load the InvoiceRow's in an array, even if there is only one in the document (without that option a single InvoiceRow would be turned into a hash value instead of an array, which would have forced me to test it).

forcecontent => 1
despite the documentation for XML::Simple stating that this option is rarely used I found it made it easier and safer to write the code: all text content is stored in the content field of a hash. This makes accessing the values a little uglier (you have to add an extra ->{content} in the expression), but in fact it saved me treating differently elements that had attributes and elements which didn't, plus it's an extra security if new attributes are added to some elements of the DTD, or for optional attributes, that would cause the generated data structure to be different depending on them being present or not (for example in OrderedQuantity the QuantityUnitCode attribute is optional).

If you use XML::Simple for data where the DTD is simpler and where attributes are always set then you might want not to use this option. In this case I found it convenient.

Finally note that XML::Simple cannot output a modified document, as it looses the order of elements in the document (once elements are assigne to a hash their order is lost), so $CAN_OUTPUT is set to 0 and the error messages are output to the console, rather than creating a new document.

This might or might not be a problem, depending on your specific case.


Michel Rodriguez <mirod@xmltwig.com>


This code is Copyright (c) 2003 Michel Rodriguez. All rights reserved.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

Comments can be sent to mirod@xmltwig.com



Ways to Rome 2 - Kourallinen Dollareita: http://www.xmltwig.com/article/ways_to_rome_2/