1

我在将父级添加到 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);

但它不会工作。还试图找到返回头节点的根的父节点,然后addchild它也不起作用。

4

2 回答 2

0

您需要创建一个新的空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>
于 2013-03-12T16:36:31.447 回答
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元素,将元素作为子元素附加到new_root并将new_root元素设置为文档的根元素。

于 2013-03-12T11:35:09.160 回答