Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get node value using XML::XPath module in Perl

Tags:

xml

perl

xpath

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.

like image 487
AnonGeek Avatar asked Apr 12 '12 10:04

AnonGeek


2 Answers

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

foreach my $node ($nodeset->get_nodelist) 
{
   print $node->string_value."\n";
}
like image 82
cjm Avatar answered Nov 11 '22 22:11

cjm


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

like image 25
mswanberg Avatar answered Nov 11 '22 22:11

mswanberg