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

Hi,
I am using XPath to retrieve the node data from an XML file. I used the following code to extract the attribute data from the file. I manually entered the attribute name in the code and I am able to extract the data properly. But when I tried to read the attribute name into a variable and use this variablename instead of actual data it is giving me errors.

Here is my XML file:
<book>
<authordata authorid="1">Name Author</authordata>
<address>name address</address>
<publication>name publication</publication>
</book>


Code with manually entered attribute name:
my $read = XML::XPath->new(filename=>'sample.xml');
my $nodedata = $read->find('//@authorid');


Code with the variablename:
$authoridno="authorid";
my $nodedata=$read->find('//$authoridno');


Could anyone please help me with this and also what should i do to extract nodename instead of attribute name in the code. Mean what should i do to extract the data inside the node authordata in the XML file. I'm doing this because ill be parsing the dtd and ill use the nodename to extract the respective data in the node.

Thanks in advance.

Replies are listed 'Best First'.
Re: XML XPath Help
by Sinistral (Monsignor) on Sep 08, 2007 at 17:21 UTC

    Code with the variablename:

    $authoridno="authorid"; Bug Here And Here | | V V my $nodedata=$read->find('//$authoridno');

    You're using single quotes, which in Perl mean "take this as exact literal" and, most importantly "do not interpolate variables". You want double quotes instead of single quotes, and if you are a belt-and-suspenders type, curly braces aren't a bad idea:

    my $nodedata=$read->find("//${authoridno}");
Re: XML XPath Help
by Jenda (Abbot) on Sep 08, 2007 at 22:53 UTC

    Apart from what Sinistral says, there is another problem. The first code calls the find() method with the string '//@authorid', the other, if it worked as intended, would call it with string '//authorid'. You are missing the @.

      Hey thanks! It worked. Seems i have to use double quotes also while using a variable name.