- 论坛徽章:
- 0
|
#!/usr/bin/perl
use integer;
$0 =~ s{.*[/\\]}{};
my $Usage = "$0 [-c charset] [-f regexp] -e element [name=value [name=value]] [-e element ...] files\n"
. " -c The charset of the input doctument.\n"
. " -f Define the field separator.\n"
. " -e Define the output xml element.\n"
. " The name=value is the attributes of the element.\n";
my $F = "";
my $charset = "UTF-8";
my @element;
while (defined($ARGV[0]))
{
if ($ARGV[0] eq '--')
{
shift;
last;
}
elsif ($ARGV[0] =~ m/^-[cC](\S*)/)
{
shift;
$charset = $1 || shift;
}
elsif ($ARGV[0] =~ m/^-[fF](.*)/)
{
shift;
$F = $1 || shift;
}
elsif ($ARGV[0] =~ m/^-[eE]\s*(\S*)/)
{
shift;
my $elem = $1 || shift;
die $Usage unless $elem;
push @element, [$elem];
}
elsif ($ARGV[0] =~ m/^(\S+)\s*=\s*['"]?(.*)["']?$/)
{
shift;
die $Usage unless @element;
push @{$element[$#element]}, [$1, xmlEscape($2)];
}
elsif ($ARGV[0] =~ m/^-/)
{
die $Usage;
}
else
{
last;
}
}
die $Usage unless $element[0];
print "<?xml version=\"1.0\" encoding=\"$charset\"?>\n";
for (my $i=0; $i<@element; $i++)
{
print "<$element[$i][0]";
for (my $j=1; $j<@{$element[$i]}; $j++)
{
print " $element[$i][$j][0]=\"$element[$i][$j][1]\"";
}
print ">\n";
}
if (length($F))
{
while (<>)
{
chomp;
next if /^\s*$/;
split /$F/o, $_, -1;
my $priority = m/[:\s](error|warning)[:\s]/i ? " priority=\"\L$1\"" : "";
print "<message$priority>\n";
for (my $i=0; $i<@_; $i++)
{
print "<F$i>", xmlEscape($_[$i]), "</F$i>\n";
}
print "</message>\n";
}
}
else
{
while (<>)
{
chomp;
next if /^\s*$/;
my $priority = m/[:\s](error|warning)[:\s]/i ? " priority=\"\L$1\"" : "";
print "<message$priority>", xmlEscape($_), "</message>\n";
}
}
for (my $i=$#element; $i>=0; $i--)
{
print "</$element[$i][0]>\n";
}
sub xmlEscape
{
my $str = shift;
return $str unless $str;
$str =~ s/&/&/g;
$str =~ s/'/'/g;
$str =~ s/"/"/g;
$str =~ s/</</g;
$str =~ s/>/>/g;
$str =~ s/([\0-\037\177])/sprintf "&#%d;", ord($1)/eg;
$str =~ s/^(\s+)/" " x length($1)/e;
return $str;
} |
|