我在向xml文档添加父级时遇到了一个问题。我得到了xml:
<book id="bk104">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>In post-apocalypse England, the mysterious
agent known only as Oberon helps to create a new life
for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
</book>我想要向图书添加parent标签,因此它将是:
<library>
<book id="bk104">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>In post-apocalypse England, the mysterious
agent known only as Oberon helps to create a new life
for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
</book>
</library>我正在使用XML::LIBXML,我已经尝试进入根目录
my $root = $doc->getDocumentElement;并创建新元素
my $new_element= $doc->createElement("library");然后
$root->insertBefore($new_element,undef);最后:
my $root = $doc->getDocumentElement;
my $new_element= $doc->createElement("library");
$parent = $root->parentNode;
$root->insertBefore($new_element,$parent);但这行不通。我还试图找到返回header节点的根的父节点,然后addchild,但也不起作用。
发布于 2013-03-13 00:36:31
您需要创建一个新的空library元素,并将其设置为文档的新根元素。然后将旧的根添加为新的子级。
use strict;
use warnings;
use XML::LibXML;
my $doc = XML::LibXML->load_xml(string => << '__END_XML__');
<book id="bk104">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>In post-apocalypse England, the mysterious
agent known only as Oberon helps to create a new life
for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
</book>
__END_XML__
my $book = $doc->documentElement;
my $library = $doc->createElement('library');
$doc->setDocumentElement($library);
$library->appendChild($book);
print $doc->toString(1);输出
<?xml version="1.0"?>
<library>
<book id="bk104">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>In post-apocalypse England, the mysterious
agent known only as Oberon helps to create a new life
for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
</book>
</library>https://stackoverflow.com/questions/15351309
复制相似问题