Accessing Sibling Elements in XML DOM using Perl? -
for problem having user enter string search provider, provider select plan information appears in console. however, cannot find out how print out select provider + other information needed in one.
for example:
vodafone || 12 months || 120gb
vodafone || 24 months || 200gb
i have made start , not mind sting input can figure out later, cannot find how firstly search select provider , print information. every provider , information within < plan > node (see xml below).
xml file
<plans> <internet> <plan> <technology>adsl2+</technology> <length>12</length> <provider>vodafone</provider> <price>60</price> <mincost>600</mincost> <data>120</data> <shaping>128</shaping> <homebundle>true</homebundle> </plan> <plan> <technology>adsl2+</technology> <length>12</length> <provider>telstra</provider> <price>80</price> <mincost>800</mincost> <data>200</data> <shaping>256</shaping> <homebundle>true</homebundle> </plan> (etc.)
and current perl file
use xml::dom; $dom_obj; $xml_file= shift; $parser = new xml::dom::parser; die "unable parse xml document\n" unless $dom_obj = $parser->parsefile($xml_file); @nodes = $dom_obj->getelementsbytagname("plan"); #return list of objects of 'plan' foreach $elem (@nodes) #for each 'plan' object { foreach $child ($elem->getchildelements) #should return each element under plan? { print $child->getnodevalue; #should print elements print " "; } print "\n"; }
i tried if-statement thinking close received errors.
foreach $elem (@nodes) { if($elem->getelementbytagname("provider")->getfirstchild->getnodevalue =~ /vodafone/){ print "$unit->getelementbytagname("provider")->getfirstchild->getnodevalue"; print " || "; print "$unit->getelementbytagname("length")->getfirstchild->getnodevalue"; print " || ";
any appreciated :)
i'm not familiar xml::dom
tend pick xml::twig
instead. this:
#!/usr/bin/perl use strict; use warnings; use xml::twig; $provider = 'vodafone'; sub print_plan_summary { ( $twig, $plan ) = @_; return unless $plan -> first_child_text('provider') eq $provider; print join ( "||", $plan -> first_child_text('provider'), $plan -> first_child_text('length')." months", $plan -> first_child_text('data'). " gb" ); } $twig = xml::twig -> new ( twig_handlers => { 'plan' => \&print_plan_summary } ) -> parsefile('yourxml.xml');
xml::twig
allows set handlers, take subsets of xml (in case plan
elements) , process them individually. because can this, can manipulate go, or 'simply' extract data them.
Comments
Post a Comment