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

<?xml version='1.0' ?> <Product name="terminal" no="...> <Module name="nw"> <SourceDir name="/testnw/nwtool" /> </Module> <Module name="hw"> <SourceDir name="/prod/hw" /> <SourceDir name="/test/hw" /> </Module> </Product>

I want to get the sourcedirectories per module wise. Tried with XML:Xpath,

Used: foreach my $Module($xp->find('//Module')->get_nodelist){ foreach my $SourceDir ($Module->find('//SourceDir')->get_nodelist){ my $dir = $SourceDir->find('@name')->string_value;

it is giving all sourcedirectories for each module. Let me know if you have any idea.

Replies are listed 'Best First'.
Re: How to get the node value of each node?
by derby (Abbot) on Aug 17, 2009 at 12:36 UTC

    I prefer XML::LibXML for XML processing:

    #!/usr/bin/perl use strict; use warnings; use XML::LibXML; my $file = shift || die "usage $0 xmlfile"; my $parser = XML::LibXML->new(); my $doc = $parser->parse_file( $file ); my $root = $doc->getDocumentElement; my @modules = $root->findnodes( '/Product/Module' ); foreach my $module ( @modules ) { my $name = $module->findvalue( '@name' ); print "Module Name: $name\n"; my @dirs = $module->findnodes( 'SourceDir/@name' ); foreach my $dir ( @dirs ) { print "\t", $dir->value, "\n"; } print "\n"; }
    which produces:
    Module Name: nw /testnw/nwtool Module Name: hw /prod/hw /test/hw

    -derby
      Thanks Derby, Kavitha
Re: How to get the node value of each node?
by Anonymous Monk on Aug 17, 2009 at 11:04 UTC
    1. That isn't XML ( not well-formed (invalid token) )
    2. That isn't a complete self-contained program (which would have warned you of your invalid XML)
    3. Use relative path $Module->find('./SourceDir') or $Module->find('SourceDir')