2012-08-04 55 views
-1

我有一個要求爲某些XML數據添加新元素。我的輸入和輸出如下。如何將新元素添加到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="[email protected]"> 
    <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="[email protected]"> 
    <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

我知道我老了 - 但通常這是一個有點模糊之前,我穿上了規格! – 2012-08-04 07:49:41

+0

沒有輸入和輸出指定。請用輸入和輸出編輯你的文章。 – RNJ 2012-08-04 07:49:43

+0

謝謝。我以爲我是盲人! – 2012-08-04 07:51:32

回答

2

該程序發現了最後<node>元素,克隆並調整日e屬性值,並將其附加到從中克隆的元素的父級。

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="[email protected]"> 
    <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="[email protected]"> 
    <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>