首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在perl中将父元素添加到xml文档

在perl中将父元素添加到xml文档
EN

Stack Overflow用户
提问于 2013-03-12 08:42:23
回答 1查看 226关注 0票数 1

我在向xml文档添加父级时遇到了一个问题。我得到了xml:

代码语言:javascript
复制
<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标签,因此它将是:

代码语言:javascript
复制
<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,我已经尝试进入根目录

代码语言:javascript
复制
my $root = $doc->getDocumentElement;

并创建新元素

代码语言:javascript
复制
my $new_element= $doc->createElement("library");

然后

代码语言:javascript
复制
$root->insertBefore($new_element,undef);

最后:

代码语言:javascript
复制
my $root = $doc->getDocumentElement;
my $new_element= $doc->createElement("library");
$parent = $root->parentNode;
$root->insertBefore($new_element,$parent);

但这行不通。我还试图找到返回header节点的根的父节点,然后addchild,但也不起作用。

EN

回答 1

Stack Overflow用户

发布于 2013-03-13 00:36:31

您需要创建一个新的空library元素,并将其设置为文档的新根元素。然后将旧的根添加为新的子级。

代码语言:javascript
复制
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);

输出

代码语言:javascript
复制
<?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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15351309

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档