in reply to XML parsing

This is why XML::Simple is anything but simple. Given:

use XML::Simple; use Data::Dumper; print Dumper XMLin do { local $/ = <DATA> }; __DATA__ <log> <entry> <date>2012-01-08</date> <text>Test</text> </entry> <entry> <date>2012-01-09</date> <text>Test</text> <text>Additional information</text> </entry> </log>

... as you can see, for each entry, the value for the "text" key is sometimes a string and sometimes an arrayref. You need to either test the value of "text" with ref to see if it's an arrayref, or pass additional options to XMLin to force it to always be an array. Once you've got a few potentially duplicable elements, this really starts to eliminate the supposed simplicity of XML::Simple.

Better to start straight out with something like XML::LibXML, which might present a more complicated API to begin with, it's at least consistent. Even if your XML gets more complex, your script doesn't have to.

Replies are listed 'Best First'.
Re^2: XML parsing
by asa (Novice) on Jan 13, 2012 at 13:30 UTC

    Thanks I will check it, but still want to know what is the wrong in this simple code. This confuses me.

    Thanks.

      The wrong thing is that if the tag is repeated, you end up with an array reference, if it's not, you end up with a string (if it contains just content and no attributes or child tags) or hash reference (if it does have attributes or children). Do see Simpler than XML::Simple.

      The code in the root node would throw a "Not a hash reference" exception if there are more <descript> tags in one desc, the node in your other node would throw "Not an array reference" if there is just one.

      You are trying to use the ForceArray option, but you failed to include "descript" in the list. That would force XML::Simple to always produce an array reference so that the second code works.

      Jenda
      Enoch was right!
      Enjoy the last years of Rome.

        Thank you.