如何使用 Perl (XML::LibXML) 将新节点添加到 NodeList
我正在尝试向现有 XML 文档添加新节点。
但是,尝试在 XML::LibXML::NodeList 中使用推送功能 结果不会改变文档。
这是一个例子:
#!/usr/bin/perl
use strict;
use XML::LibXML;
my $parser = XML::LibXML->new();
my $xml_string =
'<example>
<books>
<category id="1">
<book isbn="a" />
<book isbn="b" />
<book isbn="c" />
</category>
<category id="2"/>
<category id="3"/>
</books>
</example>';
my $doc = $parser->parse_string($xml_string);
my $category_nodelist = $doc->findnodes('//category[@id="1"]');
my $book_el = $doc->ownerDocument->createElement('book');
$book_el->setAttribute("isbn", "d");
$category_nodelist->push($book_el);
print $doc->toString(1);
I'm trying to add a new node to an existing XML document.
However, trying to use the push function in a XML::LibXML::NodeList result does not change the document.
Here's an example:
#!/usr/bin/perl
use strict;
use XML::LibXML;
my $parser = XML::LibXML->new();
my $xml_string =
'<example>
<books>
<category id="1">
<book isbn="a" />
<book isbn="b" />
<book isbn="c" />
</category>
<category id="2"/>
<category id="3"/>
</books>
</example>';
my $doc = $parser->parse_string($xml_string);
my $category_nodelist = $doc->findnodes('//category[@id="1"]');
my $book_el = $doc->ownerDocument->createElement('book');
$book_el->setAttribute("isbn", "d");
$category_nodelist->push($book_el);
print $doc->toString(1);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要将新节点插入到文档中,请使用
To insert the new node into the document, use
请注意,XML 是基于树的数据结构。
XML::LibXML
是一个 libxml2 解析器,用于从 XML 数据构造树数据结构。XML::LibXML::NodeList
是与您的搜索条件匹配的节点列表。因此,向此列表添加新节点不会对 XML 进行任何更改。要添加新节点,首先从节点列表中找到该节点并调用合适的子节点
等等。希望这对您有帮助。
Please note that XML is a TREE-based data structure.
XML::LibXML
is a libxml2 parser to construct the tree data structure from a XML data.XML::LibXML::NodeList
is a LIST of nodes matching your search criteria. So, adding a new node to this list will not make any change to the XML.To add a new node, first find the node from your nodelist and call the suitable sub
and many more. Hope this will be helpful to you.
快速浏览一下 The Fine Manual 让我觉得你应该使用 DOM 接口,而不是推送和弹出(正如您所发现的,它们只是修改列表,而不是底层 DOM)。
A quick perusal of The Fine Manual makes me think that you should be using the DOM interface, not push and pop (which do nothing more than modifying the list, not the underlying DOM, as you found out).