XML::LibXML 替换元素值 [英] XML::LibXML replace element value
问题描述
我想替换 xml 文件中元素的VAL1"值
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');
错误是无法通过包XML::LibXML::Element..."找到对象方法setValue"
The errror is get is "Can't locate object method "setValue" via package "XML::LibXML::Element..."
推荐答案
你从哪里得到 setValue
的?没有 XML::LibXML 对象有这样的方法.
Where did you get setValue
from? No XML::LibXML object has such a method.
此外,一个元素没有值,所以你绝对不能设置它.
Furthermore, an element doesn't have a value, so you definitely cannot set it.
"VAL1
" 是元素的子节点的值,一个 文本节点.
"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');
这篇关于XML::LibXML 替换元素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!