如何使用 Perl (XML::LibXML) 将新节点添加到 NodeList

发布于 2024-12-24 03:04:34 字数 913 浏览 5 评论 0原文

我正在尝试向现有 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 技术交流群。

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

发布评论

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

评论(3

女皇必胜 2024-12-31 03:04:34

要将新节点插入到文档中,请使用

$category_nodelist->[0]->appendChild($book_el);

To insert the new node into the document, use

$category_nodelist->[0]->appendChild($book_el);
若沐 2024-12-31 03:04:34

请注意,XML 是基于树的数据结构。 XML::LibXML 是一个 libxml2 解析器,用于从 XML 数据构造树数据结构。
XML::LibXML::NodeList 是与您的搜索条件匹配的节点列表。因此,向此列表添加新节点不会对 XML 进行任何更改。

要添加新节点,首先从节点列表中找到该节点并调用合适的子节点

appendChild
addChild
addSibling

等等。希望这对您有帮助。

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

appendChild
addChild
addSibling

and many more. Hope this will be helpful to you.

楠木可依 2024-12-31 03:04:34

快速浏览一下 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).

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