【问题标题】:To replace a number with strings in an XML file using a Perl script [duplicate]使用 Perl 脚本将数字替换为 XML 文件中的字符串 [重复]
【发布时间】:2021-02-01 04:32:54
【问题描述】:

我有一个 XML 文件。我需要将comment="18" 中的数字替换为comment="my string",其中我的字符串来自我的@array($array[18] = my string)。

 <rule ccType="inst" comment="18" domain="icc" entityName="thens"  entityType="toggle" excTime="1605163966" name="exclude" reviewer="hpanjali" user="1" vscope="default"></rule>

这是我尝试过的。

while (my $line = <FH>) {
      chomp $line;
      $line =~ s/comment="(\d+)"/comment="$values[$1]"/ig;
      #print "$line \n";
      print FH1 $line, "\n";
}

【问题讨论】:

  • 你试过什么?你有什么问题?请向我们展示您的代码。

标签: regex xml perl


【解决方案1】:

这里是一个使用XML::LibXML的例子:

use strict;
use warnings;
use XML::LibXML;

my $fn = 'test.xml';
my @array = map { "string$_" } 0..20;
my $doc = XML::LibXML->load_xml(location => $fn);
for my $node ($doc->findnodes('//rule')) {
    my $idx = $node->getAttribute('comment');
    $node->setAttribute('comment', $array[$idx]);
}
print $doc->toString();

【讨论】:

  • 谢谢。我不是 perl 专家。我知道简单的perl。我试过这个 while (my $line = ) { chomp $line; $line =~ s/comment="(\d+)"/comment="$values[$1]"/ig; # print "$line \n";打印 FH1 $line, "\n";并认为使用 XML perl 模块可能有有效的方法来做到这一点,因此我问了这个问题。非常感谢您的回答。
【解决方案2】:

这是一个XML::Twig 示例。这与XML::LibXML example 的想法基本相同,使用不同的工具以不同的方式完成:

use XML::Twig;

my $xml =
qq(<rule ccType="inst" comment="18"></rule>);

my @array;
$array[18] = 'my string';

my $twig = XML::Twig->new(
    twig_handlers => {
        rule => \&update_comment,
        },
    );
$twig->parse( $xml );
$twig->print;

sub update_comment {
    my( $t, $e ) = @_;
    my $n = $e->{att}{comment};
    $e->set_att( comment => $array[$n] );
    }

【讨论】:

  • 谢谢。我不是 perl 专家。我知道简单的perl。我试过这个 while (my $line = ) { chomp $line; $line =~ s/comment="(\d+)"/comment="$values[$1]"/ig; # print "$line \n";打印 FH1 $line, "\n";并认为使用 XML perl 模块可能有有效的方法来做到这一点,因此我问了这个问题。非常感谢您的回答。
猜你喜欢
  • 1970-01-01
  • 2014-05-17
  • 1970-01-01
  • 2016-09-03
  • 2015-05-05
  • 2013-10-28
  • 1970-01-01
  • 2012-09-15
  • 1970-01-01
相关资源
最近更新 更多