in reply to Perl XPath

Your code affects two title nodes at once because your XPath expression matches two title nodes:

/catalog/book/titles/title[ $i+1 ]

You will need to either make your XPath expression match the specific book you are currently modifying:

/catalog/book[ $j ]/titles/title[ $i+1 ]

... or you have to remove the text node from the current element and append your own text node. See XML::LibXML::Element->appendTextChild and XML::LibXML::Node->removeChildNodes:

my $element = ...; $element->removeChildNodes(); $element->appendTextNode("Hello!");

Replies are listed 'Best First'.
Re^2: Perl XPath
by GoForIt (Novice) on Feb 27, 2012 at 19:55 UTC

    Hi,

    Thanks for your response.

    Is there a way that I could pass a node to setNodeText()? I'm able to retrieve the different node values using getNodeText() method by passing the $node parameter. I'm assuming that I could do the same for setNodeText() method but somehow the method doesn't recognize the $node in XPath.

    Thanks

      I assume once you have the XML::LibXML::Text node, you can use ->replaceData or ->setData to change the values. But I've never done anything like it using XML::LibXML, so you'll have to find out whether it works yourself.

        The problem with that route is that it fails for elements with zero or more than one text child nodes. That may not be an issue here.

        I used the below approach to replace the node value.

        my $parent = $node->getParentNode(); $parent->removeChild($node); my $element = XML::XPath::Node::Element->new('category +'); my $attr = XML::XPath::Node::Attribute->new($key, $val +ue); $element->appendAttribute($attr); $result = $parent->appendChild($element);

        It works fine but the execution time is long. I've about 1000 nodes to change and the script takes 40 minutes to finish.

        Is this a bad approach?