Get the node value using the XML :: XPath module in Perl

I use the code below to get the node value from an XML file:

use XML::XPath;
use XML::XPath::XMLParser;

my $pt1 = XML::XPath->new(filename => 'test1.xml');

my $nodeset = $pt1->find('/file1/table/tname'); 

foreach my $node ($nodeset->get_nodelist) 
{
   print $node->getNodeValue."\n";
}

The contents of "test1.xml" is as follows:

<file1>
    <table>
        <tname>_sys_ident</tname>
        <ttype>regular</ttype>
        <col>
            <name>_sys_ident_asp</name>
            <type>varchar(16)</type>
            <fkey>_sys_asp</fkey>
            <attr>PRIMARY KEY</attr>
        </col>
    </table>
</file1>

I want to print the value of tname (i.e. _sys_ident ). But the above code doesn't print anything.

If I use the following for loop:

print XML::XPath::XMLParser::as_string($node);

then it gives the following result:

<tname>_sys_ident_asp</tname>

I do not need this full node name and value string. I just want a node value. This is the first time I'm trying to use XML and XPath. Please tell me what I am doing wrong.

+5
source share
2 answers

getNodeValue attribute . string_value:

foreach my $node ($nodeset->get_nodelist) 
{
   print $node->string_value."\n";
}
+7

xpath, try/file1/table/tname/text()

+1

All Articles