XML::LibXML 替换元素值

发布于 2024-12-20 07:39:11 字数 550 浏览 0 评论 0原文

我想替换 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北城挽邺 2024-12-27 07:39:11

元素没有值,因此它没有 setValue 方法。

VAL1”是元素子节点的值,a 文本节点

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

不幸的是,这并不完全安全。如果元素有多个文本子节点怎么办?如果根本没有怎么办?

更安全的方法是获取该元素,删除其所有作为文本节点的子节点(可以通过删除其所有子节点轻松完成),然后添加具有所需值的新文本节点。

my ($application_id_node) = $root->findnodes('/testing/application_id');
$application_id_node->removeChildNodes();
$application_id_node->appendText('VAL2');

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');
稀香 2024-12-27 07:39:11

Node 中没有 setValue 方法或Element 类,请参阅文档以获取可用方法列表。您可以删除元素的子元素并附加新的文本节点,如下所示:

$elem->removeChildNodes();
$elem->appendText('VAL2');

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');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文