XML::LibXML replace element value
Asked Answered
C

2

10

I want to replace a "VAL1" value of an element in xml file

For some reason it does not work for me:

   <testing>
<application_name>TEST</application_name>
<application_id>VAL1</application_id>
<application_password>1234</application_password>
   </testing>

my $parser =XML::LibXML->new();
$tree   =$parser->parse_file($xml);
$root   =$tree->getDocumentElement;
my ($elem)=$root->findnodes('/testing/application_id');
$elem->setValue('VAL2');    

The errror is get is "Can't locate object method "setValue" via package "XML::LibXML::Element..."

Clint answered 7/12, 2011 at 7:16 Comment(0)
R
23

An element doesn't have a value, so it doesn't have a setValue method.

"VAL1" is the value of the the element's child node, a text node.

my ($application_id_text) = $root->findnodes('/testing/application_id/text()');
$application_id_text->setData('VAL2');

Unfortunately, that's not completely safe. What if the element has multiple text child nodes? What if it doesn't have any at all?

The safer way is to grab the element, delete all of its children that are text nodes (which can easily done by removing all of its child nodes), and add a new text node with the desired value.

my ($application_id_node) = $root->findnodes('/testing/application_id');
$application_id_node->removeChildNodes();
$application_id_node->appendText('VAL2');
Radiotherapy answered 7/12, 2011 at 8:6 Comment(0)
R
8

There is no setValue method in Node or Element classes, see the docs for list of available methods. You can remove children of the element and append new text node like this:

$elem->removeChildNodes();
$elem->appendText('VAL2');
Rooted answered 7/12, 2011 at 7:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.