如何向XML数据添加新元素

时间:2012-08-04 07:47:13

标签: xml perl

我需要为某些XML数据添加新元素。我的输入和输出如下。

在这里,我将在输入中给出DINESH,并且必须创建新元素。 oid值必须从上面加1。

<node nspc="DEFAULT" name="CEN509_DINESH" modl="MDL_DINESH" lcmd="node.sh" oid="5" />

感谢您的帮助

输入:

<?xml version="1.0" encoding="UTF-8"?>
<root user="gaia" pass="XY6jKWTTBfU=" desc="default user" mail="dinesh@gmail.com">
  <node nspc="DEFAULT" name="CEN509_ASONI" modl="MDL_ASONI" lcmd="node.sh" oid="3" />
  <node nspc="DEFAULT" name="CEN509_ASTI" modl="MDL_ASTI" lcmd="node.sh" oid="4" />
</root>

输出

<?xml version="1.0" encoding="UTF-8"?>
<root user="gaia" pass="XY6jKWTTBfU=" desc="default user" mail="dinesh@gmail.com">
  <node nspc="DEFAULT" name="CEN509_ASONI" modl="MDL_ASONI" lcmd="node.sh" oid="3" />
  <node nspc="DEFAULT" name="CEN509_ASTI" modl="MDL_ASTI" lcmd="node.sh" oid="4" />
  <node nspc="DEFAULT" name="CEN509_DINESH" modl="MDL_DINESH" lcmd="node.sh" oid="5" /> 
</root>

1 个答案:

答案 0 :(得分:2)

该程序找到最后一个<node>元素,克隆它并调整属性值,并将其附加到从中克隆的元素的父元素。

use strict;
use warnings;

use XML::LibXML;

my $doc = XML::LibXML->load_xml(string => <<'END', no_blanks => 1);
<?xml version="1.0" encoding="UTF-8"?>
<root user="gaia" pass="XY6jKWTTBfU=" desc="default user" mail="dinesh@gmail.com">
  <node nspc="DEFAULT" name="CEN509_ASONI" modl="MDL_ASONI" lcmd="node.sh" oid="3" />
  <node nspc="DEFAULT" name="CEN509_ASTI" modl="MDL_ASTI" lcmd="node.sh" oid="4" />
</root>
END


my $input = 'DINESH';

my ($lastnode) = $doc->findnodes('/root/node[last()]');
my $newnode = $lastnode->cloneNode;

my %attr = map { $_ => $newnode->getAttributeNode($_) } qw/ name modl oid /;

my $val;

$val = $attr{name}->getValue;
$val =~ s/[^_]+$/$input/;
$attr{name}->setValue($val);

$val = $attr{modl}->getValue;
$val =~ s/[^_]+$/$input/;
$attr{modl}->setValue($val);

$val = $attr{oid}->getValue;
$attr{oid}->setValue($val + 1);

$lastnode->parentNode->appendChild($newnode);

print $doc->toString(1);

<强>输出

<?xml version="1.0" encoding="UTF-8"?>
<root user="gaia" pass="XY6jKWTTBfU=" desc="default user" mail="dinesh@gmail.com">
  <node nspc="DEFAULT" name="CEN509_ASONI" modl="MDL_ASONI" lcmd="node.sh" oid="3"/>
  <node nspc="DEFAULT" name="CEN509_ASTI" modl="MDL_ASTI" lcmd="node.sh" oid="4"/>
  <node nspc="DEFAULT" name="CEN509_DINESH" modl="MDL_DINESH" lcmd="node.sh" oid="5"/>
</root>