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

I saw a related question when i was searching, but mine might be a bit different? i just started using perl 3 days ago, and its the second programming language i learnt. (first was matlab!) in any case, could someone please teach me how i can get the text i want? thanks!! here's my code:
#!/usr/bin/perl -w use XML::DOM; use strict; my ($file, @rubbish) = @ARGV; if ($#ARGV > 0 ){ die; } my $parser = new XML::DOM::Parser; my $doc = $parser->parsefile($file); my $root = $doc->getDocumentElement(); print "$root\n"; scanner($root); sub scanner { my ($rt) = @_; my $i=0; foreach my $track ($rt->getElementsByTagName('track')){ foreach my $ping ( $track->getChildNodes()){ foreach my $nde ( $ping->getChildNodes()) { #my $nde = $nee->getNextSibling; if ($nde->getNodeType == ELEMENT_NODE) { #$log->info( $i.$nde->getTagName()); print $i++, " ELEMENT ", $nde->getNodeValue(), "\n"; } scanner( $nde ); } } } } } my file looks sth like this: <track name="linguist.segments" type="primary"> - <el index="0" start="0.44" end="0.56"> <attribute name="semantics">abstract</attribute> <attribute name="type">description/assertion</attribute> </el> - <el index="1" start="0.56" end="0.76"> <attribute name="semantics">abstract</attribute> <attribute name="type">command</attribute> </el> </track>
i want to be able to extract 'description/assertion' and 'command' from my code. Thanks so much! Ok, I figured out what is wrong. The text node is a child node of the element node lol.

Replies are listed 'Best First'.
Re: XML::DOM help
by pc88mxer (Vicar) on Jul 10, 2008 at 06:48 UTC
    Learning XPath might be useful for this problem. Here's how you would get your data using XML::XPath:
    use XML::XPath; my $xp = XML::XPath->new(ioref => \*DATA); my $nodeset = $xp->find('/track/el/attribute[@name="type"]/text()'); # foreach my $node ($nodeset->get_nodelist) { print "FOUND\n\n", $node->getValue, "\n\n"; }
      thanks loads, xpath sure looks tons neater =) maybe i'd use that next time (adding on to someone's code now)
Re: XML::DOM help
by mirod (Canon) on Jul 10, 2008 at 07:57 UTC

    Actually I wouldn't use XML::DOM these days, nor XML::XPath either. XML::LibXML is better maintained and much, much more powerful. The code would be very similar, as XML::LibXML supports the DOM API. If you want to stick to XML::DOM, maybe because you can't install libxml2 on which XML::LibXML is based, have a look at XML::DOM::XPath, that will make XML::DOM a little easier to use.