如何在perl中使用xpath为元素插入祖先和兄弟?

时间:2014-07-13 08:51:07

标签: xml perl xpath perl-module

我想在perl中使用xpath为元素插入一个祖先和兄弟。

这是我的输入

<docinfo:hier>
<docinfo:hierlev role="ancestor">
<heading>
<title>CENTRAl</title>
</heading>
<docinfo:hierlev role="ancestor">
<heading>
<title>A</title>
</heading>
<docinfo:hierlev role="ancestor">
<heading><title>AC</title></heading>
<docinfo:hierlev role="ancestor">
<heading><title>THE ACTUARIE</title></heading>
<docinfo:hierlev role="ancestor">
<heading><title>CHAPTER VII </title></heading>
<docinfo:hierlev role="me">
<heading>
<title>46. Terms and conditions of Chairman and Members of Board.</title>             
</heading>
</docinfo:hierlev>
</docinfo:hierlev>
</docinfo:hierlev>
</docinfo:hierlev>
</docinfo:hierlev>
</docinfo:hierlev>

我想要这样的输出:

##表示新插入的元素

<docinfo:hier>
<docinfo:hierlev role="ancestor">
<heading><title>Rules</title></heading># here i want change the text
<docinfo:hierlev role="ancestor">##
<heading>##
<title>Rule</title>##
</heading>##
<docinfo:hierlev role="ancestor">
<heading><title>A</title></heading>
<docinfo:hierlev role="ancestor">
<heading><title>AC</title></heading>
<docinfo:hierlev role="ancestor">
<heading><title>THE ACTUARIE</title></heading>
<docinfo:hierlev role="ancestor">
<heading><title>CHAPTER VII </title></heading>
<docinfo:hierlev role="me">
<heading>
<title>46. Terms and conditions of Chairman and Members of Board.</title>
</heading>
</docinfo:hierlev>
</docinfo:hierlev>
</docinfo:hierlev>
</docinfo:hierlev>
</docinfo:hierlev>
</docinfo:hierlev>##
</docinfo:hierlev>
</docinfo:hier>

这是我的源代码

当我运行代码时,它只插入元素标题。

#!/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('/LEGDOC/docinfo/docinfo:hier/docinfo:hierlev/heading');

my $new_element= $doc->createElement("docinfo:hierlev");
my $new_element= $doc->createElement("heading");
my $new_element= $doc->createElement("title");
$new_element->appendText('rule');
$ref_node->parentNode->insertAfter($new_element, $ref_node);

print $root->toString(1);

1 个答案:

答案 0 :(得分:0)

正如Friedo建议的那样,不要将每个元素添加到$ new_element变量中,而是覆盖它。

我的Perl有点生疏,但我认为你需要的东西沿着下面的方向。我知道这可以用更少的代码行完成,但为了清楚起见,我试图将步骤分开。

  -- create distinct nodes for each level
  my $newDocInfoElement = $doc->createElement("docinfo:hierlev");
  my $newHeadingElement = $doc->createElement("heading");
  my $newTitleElement = $doc->createElement("title");
  $newTitleElement->appendText('rule');

  --append them into the structure that you want
  $newHeadingElement->addChild($newTitleElement);
  $newDocInfoElement->addChild($newHeadingElement);

  --add the whole structure to your XML
  $ref_node->parentNode->insertAfter($newDocInfoElement, $ref_node);

希望这是有帮助的。