in reply to XML::Twig efficiency with attributes

I want to find the 'Instruction' element where 'Type'='Motor'.

->first_child('Instruction[@Type="Motor"]')

#!/usr/bin/perl use strict; use warnings; use XML::Twig; # build a new file in the output format. my $Output_file_name = 'testOutput.xml'; my $outRoot = XML::Twig::Elt->new('Motors'); #process input XML data my $twig = new XML::Twig( twig_roots=>{ Sheet=>\&motors } ); $twig->parse(*DATA); #output results $outRoot->set_pretty_print('indented'); $outRoot->print;#_to_file($Output_file_name); sub motors{ my ($twig, $elt)=@_; my $motor = $elt->first_child('Instruction[@Type="Motor"]'); my $motorID = $motor->att('ID'); my $newRoot = $outRoot->insert_new_elt( 'Motor'=>{ Name=> $motor->att('Name'), ID => $motorID } ); my %InOut=(); for ( $elt->children( 'Input|Output' ) ){ $InOut{'Motor_'.$_->gi}[ $_->att('ID') ] = $_->att('Text'); } my $xpath='Wire[@ToID="'.$motorID.'" or @FromID="'.$motorID.'"]'; for my $c ( $elt->children( $xpath ) ){ my ($id,$text); if ( $c->att('ToID' ) eq $motorID ){ $id = $c->att( 'FromID' ); $text = $c->att( 'ToText' ); } else { $id = $c->att( 'ToID' ); $text = $c->att( 'FromText' ); } $newRoot->insert_new_elt('last_child', $text, $InOut{$text}[$id] ) }; }
poj

Replies are listed 'Best First'.
Re^2: XML::Twig efficiency with attributes
by timmmy (Initiate) on Jun 03, 2014 at 14:14 UTC

    Perfect. Thanks!