2

我有以下 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>

我需要将 value1 修改为其他内容,到目前为止,我可以编写以下 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();

但什么都没有改变!任何想法都非常感谢。

问候,贝扎德

4

2 回答 2

1

您的代码存在一些问题:

  • 它不编译:->set_att不是一个有效的语句

  • 使用use warnings会让你知道 XMLOUT 有问题,你会得到print() on unopened filehandle XMLOUT,如果你想输出到文件,使用print_to_file

  • 你的处理程序是 on 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);
于 2013-04-11T13:07:44.447 回答
1

您已经为元素设置了一个XML::Twig处理程序parameter,但您的数据中没有任何内容,因此没有任何内容被修改。

此外

  • use strict很好,但你也应该use warnings

  • XMLOUT您永远不会在句柄上打开文件。使用模块的print_to_file方法更简单,避免必须自己打开文件

认为您想要做的是查找元素的name属性property并将它们设置为其他值,如果它们当前等于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>
于 2013-04-11T13:19:09.847 回答