perl - With XML::Twig, is there a way of find a 'first_child' with a particular attribute? -
i've xml looks this:
<?xml version="1.0" encoding="utf-8"?> <dataset> <category> <name mode="source">somename</name> <name mode="destination">someothername</name> <content>some text here</content> </category> </dataset> what i'm trying process 'category', , extract different name based on context.
i've tried iterating children - works:
use strict; use warnings; use xml::twig; sub process_category { ( $twig, $category ) = @_; $cat_name; foreach $name ( $category->children('name') ) { if ( $name->att('mode') eq 'source' ) { $cat_name = $name->text; } } print "$cat_name ", $category->first_child_text('content'), "\n"; } $twig = xml::twig->new( twig_handlers => { 'category' => \&process_category } ) ->parse( \*data ); __data__ <?xml version="1.0" encoding="utf-8"?> <dataset> <category> <name mode="source">somename</name> <name mode="destination">someothername</name> <content>some text</content> </category> </dataset> however i'm wondering - there better way iterating elements? can't figure out if first_child supports attribute search, or if there's method same.
use xml::twig's get_xpath method search matching values in attributes. example:
my $cat_name = $category->get_xpath('./name[@mode="source"]', 0)->text; by default, get_xpath returns array. passing "0", first element of array passed (which need , there 1 match anyway). then, text pulled out ->text. use , can delete loop.
Comments
Post a Comment