perl - What is the correct way to parse XML using XML::TreeBuilder -


i need parse following xml:

<response>    <entity id="1">       <exists>y</exists>    </entity>     <entity id="2">       <exists>y</exists>        <attributes>          <attribute name="user">root</attribute>       </attributes>        <links>          <link type="hard">             <entity id="1"/>          </link>       </links>    </entity> </response> 

there 2 child "entity" elements in "response" element.
following code return 3 "entity" elements:

my $tree = xml::treebuilder->new(); $tree->parse($responsexml);  $response = $tree->find_by_tag_name('response'); foreach $entity ($response->find_by_tag_name('entity')) {    print "$entity\n"; } 

this code returns "entity" element child of "link" element.
need "entity" elements childs of "response" element.
correct way it?
this?

my @elements = $response->content_list(); foreach $element (@elements) {    if (ref($element) && $element->tag() eq "entity")    {       #process entity element       $id = $element->attr("id");       print "entity id=$id\n";    } } 

is appoach good?

lineage_tag_names() (refer html::element's documentation) return list of ancestors of element. 0th ancestor parent.

program

#!/usr/bin/env perl  use strict; use warnings;  use xml::treebuilder;  $tree = xml::treebuilder->new(); $tree->parse( \*data );  $response = $tree->find_by_tag_name('response'); $entity ( $response->find_by_tag_name('entity') ) {     $immediate_parent = ( $entity->lineage_tag_names() )[0];     if ( $immediate_parent eq 'response' ) {         print $entity->as_xml();         print '_' x 50, "\n";     } }  __data__ <response>    <entity id="1">       <exists>y</exists>    </entity>     <entity id="2">       <exists>y</exists>        <attributes>          <attribute name="user">root</attribute>       </attributes>        <links>          <link type="hard">             <entity id="1"/>          </link>       </links>    </entity> </response> 

output

<entity id="1">       <exists>y</exists>    </entity> __________________________________________________ <entity id="2">       <exists>y</exists>        <attributes>          <attribute name="user">root</attribute>       </attributes>        <links>          <link type="hard">             <entity id="1"></entity>          </link>       </links>    </entity> __________________________________________________ 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -