Hello there, I'm trying to find and replace a string value in XML. I've the below code so far.
#!C:/Perl/bin/perl.exe -w #use strict; use XML::XPath; use Data::Dumper; use XML::XPath::XMLParser; my $xp = XML::XPath->new(filename => "new.xml"); my $nodeset = $xp->findnodes('/catalog/book/titles/title'); my @n = ("value one", "value two"); print $nodeset->size; my $i = 0; foreach my $node ($nodeset->get_nodelist) { print "\nGET: " . $xp->getNodeText($node) . "\n"; print "\nSET: " . $xp->setNodeText('/catalog/book/titles/title['." +$i+1".']', $n[$i]) . "\n"; $i++; } open('FILE', '>output.xml'); my $nodes = $xp->find('/'); foreach my $node ($nodes->get_nodelist) { print FILE XML::XPath::XMLParser::as_string($node); } close(FILE);
My sample XML file
<?xml version="1.0"?> <catalog> <book> <author>Gambardella, Matthew</author> <titles> <title>Book 1 </title> <title>Book 2 </title> </titles> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML.</description> </book> <book> <author>Ralls, Kim</author> <titles> <title>Book 3 </title> <title>Book 4 </title> </titles> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description> </book> </catalog>
I need to pass each node value to the setNodeText method. The XPath I've currently sets two child nodes at a time.
For example, I'd like to retrieve Book 1 through 4 one at a time and set each node value to a different value. In my code, when I try to set Book 1, it sets Book 3 to the same value. Likewise, when I try to set Book 2, the value of Book 4 is overwritten. Is there a way that I could pass one node to the setNodeText() method?
I appreciate any input.
Thanks
In reply to Perl XPath by GoForIt
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |