2013-04-11 129 views
2

我有下面的XML:如何替換XML屬性名值

<resources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <resource id="kig" type="com.ac.resourcedata.xml" site="ki"> 
    <property name="name1">value1</property> 
    <property name="name2">value2</property> 
    </resource> 
</resources> 

我需要修改值1到別的東西, 和下面的Perl腳本是什麼,我可以迄今組成:

use strict; 
use XML::Twig; 

my $file = $ARGV[0]; 
my $twig=XML::Twig->new( 
    twig_handlers => { 
     parameter => sub { 
      if ($_->att('name') eq 'name1') { 
       ->set_att(new value) 
      } 
     } 
    }, 
    pretty_print => 'indented', 
); 

$twig->parsefile($file); 

$twig->print(\*XMLOUT) or 
die "Failed to write modified XML file:$!\n"; 

close XMLOUT; 

$twig->flush(); 

但沒有什麼變化! 任何想法真的很感激。

問候, Behzad

回答

1

有你的代碼的幾個問題:

  • 它不會編譯:->set_att是不是一個有效的語句

  • 使用use warnings會讓你知道這裏有些不對勁機智XMLOUT,你會得到print() on unopened filehandle XMLOUT,如果要輸出到文件,使用print_to_file

  • 您的處理程序是parameter,當你要更新的元素稱爲property,實際上你甚至可以指定你只想更新property當屬性名稱是name1直接在處理程序觸發:property[@name="name1"]

  • 它看起來像你想要的是改變屬性的文本,而不是一個屬性

固定了這一切後,你會得到

#!/usr/bin/perl 

use strict; 
use warnings; 

use autodie qw(open); 

use XML::Twig; 

my $file = $ARGV[0]; 
my $twig=XML::Twig->new( 
    twig_handlers => { 
     'property[@name="name1"]' => sub { $_->set_text('value') } 
    }, 
    pretty_print => 'indented', 
); 

$twig->parsefile($file); 
$twig->print_to_file($file); 
1

你設置了一個XML::Twig處理程序parameter元素,但也有非在你的數據,因此沒有被修改。

此外

  • use strict是好的,但你也應該use warnings

  • 你永遠不打開的XMLOUT手柄的文件。它更容易使用模塊的print_to_file方法,以避免打開一個文件自己

覺得你想要做是尋找property元素name屬性並將其設置爲別的東西,如果他們目前等於name

該代碼會爲你做的。

use strict; 
use warnings; 

use XML::Twig; 

my ($file) = @ARGV; 

my $twig = XML::Twig->new( 
    twig_handlers => { 
     property => sub { 
      if ($_->att('name') eq 'name1') { 
       $_->set_att(name => 'something else'); 
      } 
     } 
    }, 
    pretty_print => 'indented', 
); 

$twig->parsefile($file); 

$twig->print_to_file('xmlout.xml'); 

輸出

<resources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <resource id="kig" site="ki" type="com.ac.resourcedata.xml"> 
    <property name="something else">value1</property> 
    <property name="name2">value2</property> 
    </resource> 
</resources>