Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Help with XML Parsing

by GrandFather (Saint)
on Jul 20, 2007 at 22:07 UTC ( [id://627893]=note: print w/replies, xml ) Need Help??


in reply to Help with XML Parsing

Generally XML strongly implies "use XML::Twig". However, unless the XML you want to process is very large, in this case I'd suggest XML::TreeBuilder is most appropriate. In particular take a look a the look_down method of HTML::Element. Consider:

use strict; use warnings; use XML::TreeBuilder; my $xml = <<XML; <root> <a attr='1'>Contents of a - 1</a> <b>Contents of b</b> <a attr='2'>Contents of a - 2</a> <c>Contents of c</c> <d>Contents of d</d> </root> XML my $root = XML::TreeBuilder->new (); $root->parse ($xml); print "All the 'a' elements\n"; for my $elt ($root->look_down ('_tag' => 'a')) { print $elt->as_XML (), "\n"; } print "All the 'b' elements\n"; for my $elt ($root->look_down ('_tag' => 'b')) { print $elt->as_XML (), "\n"; } print "All the 'a' elements with attr='2'\n"; for my $elt ($root->look_down ('_tag' => 'a', 'attr' => '2')) { print $elt->as_XML (), "\n"; }

Prints:

All the 'a' elements <a attr="1">Contents of a - 1</a> <a attr="2">Contents of a - 2</a> All the 'b' elements <b>Contents of b</b> All the 'a' elements with attr='2' <a attr="2">Contents of a - 2</a>

DWIM is Perl's answer to Gödel

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-04-19 06:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found