Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Xml 如何为元素插入祖先_Xml_Perl_Xpath_Xml Libxml - Fatal编程技术网

Xml 如何为元素插入祖先

Xml 如何为元素插入祖先,xml,perl,xpath,xml-libxml,Xml,Perl,Xpath,Xml Libxml,我想插入B1元素作为“C”元素的祖先。下面我粘贴了示例xml和perl代码 输入 <A> <B> <C> <D>name</D> <E>number</E> </C> </B> </A> <A> <B> <B1></B1> <C>

我想插入B1元素作为“C”元素的祖先。下面我粘贴了示例xml和perl代码

输入

  <A>
   <B>
    <C>
     <D>name</D>
     <E>number</E>
    </C>
   </B>
  </A>
<A>
  <B>
   <B1></B1>
     <C>
      <D>name</D>
      <E>number</E>
     </C>
  </B>
  </A>

必须删除内部节点并将其插入新元素:

#!/usr/bin/perl
use warnings;
use strict;

use XML::LibXML;

my $doc         = 'XML::LibXML'->load_xml( location => 'mytest.xml' );
my $root        = $doc->getDocumentElement();
my $new_element = $doc->createElement('B1');

my ($parent) = $doc->findnodes('/A/B');
my ($inner)  = $parent->findnodes('C');

$new_element->addChild($inner);
$parent->addChild($new_element);

print $root->toString();
或者,对于较短的代码,使用:

#!/usr/bin/perl

use strict;

use warnings;

use XML::LibXML;

my $parser = XML::LibXML->new;

my $doc = $parser->parse_file("mytest.xml");

my $root = $doc->getDocumentElement();

my ($ref_node) = $doc->findnodes('\A\B');

my $new_element= $doc->createElement("B1");

$ref_node->parentNode->insertAfter($new_element, $ref_node);

print $root->toString(1);
#!/usr/bin/perl
use warnings;
use strict;

use XML::LibXML;

my $doc         = 'XML::LibXML'->load_xml( location => 'mytest.xml' );
my $root        = $doc->getDocumentElement();
my $new_element = $doc->createElement('B1');

my ($parent) = $doc->findnodes('/A/B');
my ($inner)  = $parent->findnodes('C');

$new_element->addChild($inner);
$parent->addChild($new_element);

print $root->toString();
open mytest.xml ;
wrap B1 A/B/C ;
save :b ;