XML::LibXML 替换元素值
我想替换 xml 文件中元素的“VAL1”值
由于某种原因,它对我不起作用:
<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”” ……”
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..."
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
元素没有值,因此它没有
setValue
方法。“
VAL1
”是元素子节点的值,a 文本节点。不幸的是,这并不完全安全。如果元素有多个文本子节点怎么办?如果根本没有怎么办?
更安全的方法是获取该元素,删除其所有作为文本节点的子节点(可以通过删除其所有子节点轻松完成),然后添加具有所需值的新文本节点。
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.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.
Node 中没有
setValue
方法或Element 类,请参阅文档以获取可用方法列表。您可以删除元素的子元素并附加新的文本节点,如下所示: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: