1

The Situation: i am currently using XML::LibXML to extract data from an XML. I combine this with the Xpath of the XML elements and I can read and replace most values in the XML. However, I cant seem to access a particular data in the first tag of the XML. It is a rather important field but I have tried a few ways and still cant can manipulate that field.

XML File:

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <test **date_time="201111031006"** xsi:noNamespaceSchemaLocation="test.xsd">
    <msg_ver>0001</msg_ver>
    <sender_id>john</sender_id>
    <recipient_id>mike</recipient_id>
 </test>

I am trying to access the date_time field(in bold) but I cant seem to do so. I copied the XPath and tried as well and it wont work. I can actually change the field and so forth but I can't change the date_time field. I am unable to even extract the data from the field let alone change it. Using the same function i can read, extract and save changes to fields , and .

My Code

 sub CHANGE_DATE()
  {
    my $parser = XML::LibXML->new();
    my $doc    = $parser->parse_file($newfile);
    my $query  = "/tradenet/@date_time"; ## this is the actual XPATH
    my($node)   = $doc->findnodes($query);
        $node->setData("$date");

    $doc->toFile($newfile);

Thank you in advance for time taken to look thru this..

Aaron Xavier
  • 73
  • 1
  • 7

2 Answers2

6

Add use warnings; and use strict; to the top of your script and it will tell you about a problem with your query. (Clue - @date_time looks like a variable name.)

Next you'll notice that tradenet is not the top-level tag in your test file.

Then, having fixed these you would find that setData() is not correct for an attribute, it's setValue().

Then it will work.

All of this you would have discovered yourself if you'd converted the script into a small test and run it yourself before posting a question.

Community
  • 1
  • 1
Richard Huxton
  • 21,516
  • 3
  • 39
  • 51
  • Thank you for the tip. My apologies for the typo as i had to edit the original XML document as it is classified. Hence the error of the XPATH name. Thanks again. – Aaron Xavier Apr 27 '12 at 07:33
0

Please try the following xPath query /test/@date_time this should work.

my $query  = '/test/@date_time'; 

Also, W3School has excellent tutorial for xPath and libXML follows the same.

http://www.w3schools.com/xpath/

Hope this will help.

rpg
  • 1,632
  • 2
  • 18
  • 34