0

I have an XML file. I need to replace the digits in comment="18" with comment="my string" where my string is from my @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>

This is what I have tried.

while (my $line = <FH>) {
      chomp $line;
      $line =~ s/comment="(\d+)"/comment="$values[$1]"/ig;
      #print "$line \n";
      print FH1 $line, "\n";
}
1
  • 2
    What have you tried? What problems are you having? Please show us your code. Commented Feb 1, 2021 at 11:40

2 Answers 2

5

Here is an example using 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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I am no expert in perl. I know simple perl. I have tried this while (my $line = <FH>) { chomp $line; $line =~ s/comment="(\d+)"/comment="$values[$1]"/ig; # print "$line \n"; print FH1 $line, "\n"; } and thought that there might be efficient ways to do this with XML perl module hence I have asked this question. Thanks a lot for your answer.
4

Here's an XML::Twig example. It's basically the same idea as the XML::LibXML example done in a different way with a different tool:

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] );
    }

1 Comment

Thanks. I am no expert in perl. I know simple perl. I have tried this while (my $line = <FH>) { chomp $line; $line =~ s/comment="(\d+)"/comment="$values[$1]"/ig; # print "$line \n"; print FH1 $line, "\n"; } and thought that there might be efficient ways to do this with XML perl module hence I have asked this question. Thanks a lot for your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.