avoid trimming trailing empty fields
[migration-tools.git] / extract_xml_tags.pl
1 #!/usr/bin/perl -w
2
3 # Copyright 2009-2012, Equinox Software, Inc.
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
19 use strict;
20
21 use Getopt::Long;
22
23 my (@tags, $infile);
24 GetOptions ("tags=s" => \@tags,
25             "infile=s" => \$infile);
26 @tags = split(/,/, join(',', @tags));
27
28 open(FH, $infile) or die "Can't open $infile for reading: $!";
29
30 while (<FH>) { 
31
32   my %tag;
33   my $xml = $_;
34
35   # Find the Evergreen bib ID
36   $xml =~ m/<datafield tag="903".+?<subfield code="a">(.+?)<\/subfield>/; 
37   my $egid = $1; 
38
39   # Find each occurrence of each tag specified
40   foreach (@tags) {
41     $tag{$_} = [ $xml =~ m/(<datafield tag="$_".+?<\/datafield>)/g ];
42   }
43
44   # Clean up the results before printing
45   my $output = '';
46   foreach my $key (sort keys %tag) {
47     my $text = join("", @{$tag{$key}});
48     $text =~ s/>\s+</></g;
49     $output .= $text;
50   }
51
52   # If we found any specified tags, print what we found.
53   if ($output ne '') {
54     print "$egid\t$output\n";
55   }
56
57 }
58
59 close(FH);