Isanchez has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks, I am uncapable of extring the text of an attribute for a particular node in this piece of code that extracts tags and text. Could you please help me to find a way to get the text from the attributes? thank you,
use File::Find; use XML::Twig; use XML::Encoding; find(\&getFolder, $dir1); @files=(); $found =0; &getFolder; sub getFolder{ # retrieve files recursively $file = $File::Find::name; # if the file is an xml file if ($file =~ /\.xml$/) { open (FILE, $file) ; $twig= XML::Twig->new(); $twig ->parsefile( $file ); $root = $twig->root; @nodes = $root->descendants; foreach $node (@nodes){ $tag = $des -> gi ; ==> here I would like to get and print out the text of the att +ributes of each node $node } } # if the file is xml close FILE; } #sub close dir1; close IN;

Replies are listed 'Best First'.
Re: retrieving attribute text with xml::twig
by mirod (Canon) on Jul 11, 2003 at 00:47 UTC

    The attributes are accessed using $_->atts , the values would then be values %{$_->atts}.

    Just for the fun here is a compact way to do this:

    #!/usr/bin/perl -w use strict; use XML::Twig; XML::Twig->new( start_tag_handlers => { _all_ => sub { print join( ' - ' => values %{$_->a +tts}), "\n"; } } ) ->parse( \*DATA); __DATA__ <doc> <elt att="first attribute">text</elt> <elt att="second attribute" att2="foo">text</elt> <elt att="bar">text</elt> </doc>
      thank you Monk Mirod, Ivo