http://qs321.pair.com?node_id=544926
Description: Project I am working on has a requirement for a quick and dirty utility to replace all the content of a given tag in a sub-directory of XML files and create amended files. This is what I have cooked up. Treated the files as text rather than XML and parsing etc. as I have had real trouble trying to install libxml etc. First posting to the Monastery, so be KIND! Kind regards all.
use diagnostics;

print "This Perl script replaces the content of a given element from a
+ series of XML updategrams\n";

print "Please enter the subdirectory of the files (do not forget to es
+cape path dividers)\n";
my $directory = <STDIN>;
chomp($directory);

print "Please enter the tagname you want to edit (just the tagname, no
+ need for angle brackets)\n";
my $tagname =<STDIN>;
chomp($tagname);

print "Please enter the new content you want to use as replacement\n";
my $new_content =<STDIN>;
chomp($new_content);

##create new substring (done here to be done only once to speed script
+)
my $newstring = "<$tagname>$new_content<\/$tagname>";
print "New tag content will appear as $newstring\n";

my $filecon = "";

opendir(DIR, $directory) or die "can't opendir $directory: $!";
while (defined($file = readdir(DIR))) {
    next if $file =~ /^\.\.?$/; 
    open(SRC, "< $directory\\$file") or die "Could not open source $di
+rectory\\$file\n";
    print "Processing file $file\n";
    while (<SRC>) {
                    chomp;
                    #print "$_\n";
                    $filecon=$filecon.$_;
                    }
    close SRC;

    #print "$filecon\n";
    $start = index($filecon, "<$tagname>");
    print "Start of tag is $start\n";
    $end=index($filecon, "<\/$tagname>");
    print "End of tag is $end\n";
#################################################
##Amendments done to here
##Replacement scheme needed after this
#################################################

    #need to replace the tag content
    $offset = $end-$start+length($tagname)+3;
    substr($filecon, $start, $offset)= $newstring;
    #print "$filecon\n";
    
    #manipulate the filename
    #$position = index($file, ".");
    #$filestem = substr($file,($position-1),-100);
    $filestem = $file;
    $newfilename = "$directory\\$filestem.$tagname.xml";
    print "Writing new file $newfilename\n";

    #write out the amended xml file
    open(OUT, "> $newfilename");
    print OUT "$filecon";    
    close OUT;
    $newfilename = "";
    $filecon = "";
}
print "The routine is finished\n";
#just to keep cmd window open for message to be seen
sleep 5;