我有一个向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>
我希望在书中添加父标签,这样就可以了:
<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
,我试图获得root
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);
但它无法正常工作。还试图找到返回头节点的root的父节点,然后addchild
,但它也不起作用。
答案 0 :(得分:0)
试试这件:
open my $in, '<:encoding(utf-8)', 'in.xml';
my $document = XML::LibXML->load_xml(IO => $in);
my $root = $document->documentElement();
my $new_root = $document->createElement('library');
$new_root->appendChild($root);
$document->setDocumentElement($new_root);
open my $out, '>:encoding(utf-8)', 'out.xml';
print $out $document->toString();
创建 new_root 元素,将 root 元素附加到 new_root 作为子元素,并将 new_root 元素设置为root文件的要素。
答案 1 :(得分:0)
您需要创建一个新的空library
元素并将其设置为文档的新根元素。然后将旧root添加为新子项。
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>