Reputation: 184
I am new to Perl, I have a task to replace or remove comment part (<!--
) in multiple XML files, after replace I need to move those multiple XML files to other directories. I am illustrating below my D:\folder1\
having many xml files a.xml
, b.xml
, c.xml
so on, after replace I need to move all the files from folder1
to D:\folder2\
.
I tried one file by replacing -
and @@@
but I don't have idea to remove comment line (<!--add aaa -->
) from xml files in directory.
My Perl code follow below
#!/usr/bin/perl
use strict;
use warnings;
my $tag = 'SHORT_DESC';
open my $input_file, '<', 'test.xml' or die $!;
open my $output_file, '>', 'test_out.xml' or die $!;
my $input;
{
local $/; #Set record separator to undefined.
$input = <$input_file>; #This allows the whole input file to be read at once.
}
$input =~ s/&/@@@/g;
$input =~ s/^- (?=<)//gm;
$input =~ s/<header[^>]*>\K\s*<header[^>]*>//gis;
close $input_file or die $!;
print {$output_file} $input;
close $output_file or die $!;
And my XML is
<?xml version = '1.0' encoding = 'UTF-8'?>
<!-- Order details-->
<order>
<Names>
<!-- Names-->
<content>This is dummy content</content>
</Names>
</order>
Upvotes: 0
Views: 135
Reputation: 241858
Use a proper XML handling module. I like XML::XSH2, a wrapper around XML::LibXML:
#! /usr/bin/perl
use warnings;
use strict;
use XML::XSH2; # To handle XML.
use Path::Tiny; # To move files around.
my ($source, $target) = @ARGV;
for my $file (path($source)->children(qr/\.xml$/)) {
xsh "open $file ; delete //comment() ; save";
path($file)->copy($target);
path($file)->remove;
}
Upvotes: 3