How do I edit an XML file with Perl?
Posted
by thebourneid
on Stack Overflow
See other posts from Stack Overflow
or by thebourneid
Published on 2010-05-25T04:55:46Z
Indexed on
2010/05/26
3:11 UTC
Read the original article
Hit count: 313
I have a movie collection catalogue with local links to folders and files for an easy access. Recently I reorganaized my entire hard disk space and I need to update the links and I'm trying to do that automatically with Perl.
I can export the data in a XML file and import it again. I can extract the new filepaths with the use of File::Find but I'm stuck with two problems. I have no idea how to connect the $title
from the new filepath with the corresponding $title
from the XML file. I'm dealing with such files for the first time and I don't know how to proceed with the replacement process. Here is what I've done till now
use strict;
use warnings;
use File::Basename;
use File::Find;
use File::Spec;
use XML::Simple;
use Data::Dumper;
my $dir_target = 'D:/Movies/';
my %titles_locations = ();
find(\&file_handler, $dir_target);
sub file_handler {
/\.iso$/ or return;
my $fn = $File::Find::name;
$fn =~ s/\//\\/g;
$fn =~ /(.*\\)(.*)/;
my $path = $1;
my $filename = $2;
my $title = (File::Spec->splitdir($fn))[2];
$title =~ s/(.*?)\s\(\d+\)$/$1/;
$title =~ s/~/:/;
$title =~ s/`/?/;
my $link_local = '<link><description>Folder</description><url>'.$path.'</url><urltype>Movie</urltype></link><link><description>'.$filename.'</description><url>'.$fn.'</url><urltype>Movie</urltype></link>' unless $title eq '';
$titles_locations{$title} = {'filename'=>$filename, 'path'=>$path };
}
my $xml_in = XMLin('somepath/test.xml', ForceArray => 1, KeepRoot => 1);
my $title = {'key1' => 'title', 'key2' => 'links'};
foreach my $link (keys %$title) {
}
print Data::Dumper->Dump([$title]);
my $xml_out = XMLout($xml_in, OutputFile => 'somepath/test_out.xml', KeepRoot=>1);
And here is a snippet of the data I need to edit. If found imdb and dvdempire link - do not touch. if found local links replace, otherwise insert. I'm willing to complete the code myself but need some directions how to proceed further. Thanks.
<title>$title</title>
.......
<links>
<link>
<description>IMDB</description>
<url>http://www.imdb.com/title/VARIABLE</url>
<urltype>URL</urltype>
</link>
<link>
<description>DVD Empire</description>
<url>http://www.dvdempire.com/VARIABLE</url>
<urltype>URL</urltype>
</link>
<link>
<description>Folder</description>
<url>OLD_FOLDERPATH</url>
<urltype>Movie</urltype>
</link>
<link>
<description>OLD_FILENAME</description>
<url>OLD_FILENAMEPATH</url>
<urltype>Movie</urltype>
</link>
</links>
© Stack Overflow or respective owner