Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Parsing XML into a simple hash

by mirod (Canon)
on Jun 21, 2001 at 16:00 UTC ( #90334=note: print w/replies, xml ) Need Help??


in reply to Pasring XML into a simple hash

And here is the ObXTW (the Obligatory XML::Twig Way), once you've fixed your XML by wrapping everything into a single element:

#!/bin/perl -w use strict; use XML::Twig; my $t= new XML::Twig( twig_handlers => { post => \&post }); $t->parse( \*DATA); sub post { my( $t, $post)= @_; # all handlers get called with those arguments # here is the magic! # gi is the element name and text is its... text! my %hash= map { $_->gi, $_->text} $post->children; # or whatever you want to do with the hash print "City: $hash{location} \n"; # if your file is small enough you don't need to purge, otherwise # it will free the memory used so far $t->purge; } __DATA__ <posts> <post> <jobnumber>1234</jobnumber> <location> somecity NJ </location> </post> <post> <jobnumber>87922</jobnumber> <location> Othercity, AK </location> </post> </posts>

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://90334]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2020-05-27 00:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If programming languages were movie genres, Perl would be:















    Results (152 votes). Check out past polls.

    Notices?