使用Perl XML :: LibXML库,我正在尝试使用循环向XML文档中的每个现有节点添加一个新节点。这是我到目前为止的尝试:
#!/usr/bin/perl -w
use 5.14.2;
use XML::LibXML;
my $filename = "xml_doc.xml";
my $parser = XML::LibXML->new();
$parser->keep_blanks(0);
my $dom = $parser->parse_file($filename);
for my $node ($dom->findnodes("/poem/stanza/v"))
{
my $elm = $dom->createElement('newnode');
$elm->appendText('This is a new node');
$_->addChild($elm);
}
say $dom->toString(1);
文件'xml_doc.xml':
<?xml version="1.0" encoding="UTF-8"?>
<poem>
<stanza>
<v>As I was going to Bonner,</v>
<v>Upon my word of honor,</v>
<v>I met a pig</v>
<v>Without a wig,</v>
<v>As I was going to Bonner.</v>
</stanza>
</poem>
程序失败,错误“无法调用方法”addChild“在batch_add_nodes.pl第16行的未定义值上。”
欢迎任何提示。
答案 0 :(得分:5)
你需要决定你的for
循环迭代器变量是$node
还是$_
: - )
如果我将$_->addChild($elm)
替换为$node->addChild($elm)
,则代码可以正常工作并提供此输出:
<?xml version="1.0" encoding="UTF-8"?>
<poem>
<stanza>
<v>As I was going to Bonner,<newnode>This is a new node</newnode></v>
<v>Upon my word of honor,<newnode>This is a new node</newnode></v>
<v>I met a pig<newnode>This is a new node</newnode></v>
<v>Without a wig,<newnode>This is a new node</newnode></v>
<v>As I was going to Bonner.<newnode>This is a new node</newnode></v>
</stanza>
</poem>