Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm parsing a simple XML structure like this one:

<?xml version="1.0"?> <Data> <Entry> <German> <Term>Vorstoss</Term> </German> <Italian> <Term></Term> </Italian> </Entry> <Entry> <German> <Term>Scheibe</Term> </German> <Italian> <Term>Cerchio</Term> </Italian> </Entry> </Data>

I'm using the following script:

#!/usr/bin/perl use strict; use warnings; use XML::Simple; my $XmlEncoded="ciao.tmex"; my $xml = XML::Simple->new(); my $LanguageName1="German"; my $LanguageName2="Italian"; my $data = $xml->XMLin($XmlEncoded); for my $entry ( @{ $data->{Entry} } ) { my $Term1 = $entry->{$LanguageName1}->{Term}; my $Term2 = $entry->{$LanguageName2}->{Term}; print "My terms: $Term1 - $Term2\n"; }

Why when a record is empty do I get a value like HASH(0x2a268f4)? And how can I avoid it and get a simple empty value? Thank you

Replies are listed 'Best First'.
Re: Parsing XML with XML::Simple
by choroba (Cardinal) on Jul 04, 2016 at 16:09 UTC
    As noted in the documentation of XML::Simple, you shouldn't be using the module in the first place.

    > STATUS OF THIS MODULE

    > The use of this module in new code is discouraged. Other modules are available which provide more straightforward and consistent interfaces. In particular, XML::LibXML is highly recommended and XML::Twig is an excellent alternative.

    But if you really insist on using the module and getting an empty string instead of the hash reference, specify

    my $xml = XML::Simple->new(SuppressEmpty => q());

    when constructing the object.

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
Re: Parsing XML with XML::Simple
by Preceptor (Deacon) on Jul 05, 2016 at 09:22 UTC

    I would refer you to this, on the problems with XML::Simple: Why is XML::Simple "discouraged"

    I would strongly suggest looking at XML::Twig instead - as an easy-to-use XML parser, that _actually_ does XML, and not some nasty hack job. If you do, your code becomes something like this:

    #!/usr/bin/env perl use strict; use warnings; use XML::Twig; my $twig = XML::Twig->new->parsefile('ciao.tmex'); foreach my $entry ( $twig->get_xpath('//Entry') ) { print "My terms: ", $entry->get_xpath('./German/Term',0)->text, " - ", $entry->get_xpath('./Italian/Term',0)->text, "\n"; }

    You can, if you prefer, also use "first_child" and "children" to navigate the XML:

    foreach my $entry ( $twig->root->children('Entry') ) { print "My terms: ", $entry->first_child('German')->first_child_text('Term'), " - ", $entry->first_child('Italian')->first_child_text('Term'), "\n"; }
Re: Parsing XML with XML::Simple
by Jenda (Abbot) on Jul 10, 2016 at 09:35 UTC

    Please see Simpler than XML::Simple for reasons not to use XML::Simple and an alternative.

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