AnonGeek
AnonGeek

Reputation: 7938

Get node value using XML::XPath module in Perl

I m using the code below to get value of node from a 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 content of 'test1.xml' is as below:

<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 in not printing anything.

If I use the following inside for loop:

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

then, it gives following output:

<tname>_sys_ident_asp</tname>

I don't want this complete node name and value string. I just want node value. This is the first time I am trying XML and XPath. Please tell me what I am doing wrong.

Upvotes: 7

Views: 10393

Answers (2)

cjm
cjm

Reputation: 62109

getNodeValue is for attribute nodes. For elements, you want the string_value method:

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

Upvotes: 9

mswanberg
mswanberg

Reputation: 1285

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

Upvotes: 1

Related Questions