1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
|
# (C) Copyright 1996-2016 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmental organisation nor
# does it submit to any jurisdiction.
use XML::Parser;
use Data::Dumper;
$in = shift;
$p1 = new XML::Parser(Style => "Tree");
$x = $p1->parsefile($in);
$y = process({}, $x->[0],$x->[1]);
$y = $y->{magics};
# Patche
if(exists $y->{page}) {
if(exists $y->{page}->{nopageid}) {
delete $y->{page}->{nopageid};
$y->{page}->{_order} = [map { $_ eq "nopageid" ? "page_id" : $_ } @{$y->{page}->{_order}}];
$y->{page}->{page_id} = "off";
}
}
if(exists $y->{drivers}) {
my @d;
foreach my $d ( keys %{$y->{drivers}} )
{
unless($d =~ /^_/) {
$y->{drivers}->{$d}->{format} = $d;
unshift @{$y->{drivers}->{$d}->{_order}}, "format";
push @d, $y->{drivers}->{$d};
}
}
$y->{drivers} = \@d;
}
json($y);
sub json {
my ($r, $depth) = @_;
print " " x $depth;
print "{\n";
my %seen = ( "_order" => 1 );
my @order = @{$r->{_order}};
my @o;
foreach my $k ( @order ) {
unless($seen{$k})
{
$seen{$k}++;
push @o, $k;
}
}
my $count = @o;
my $i = 0;
foreach my $k ( @o ) {
print " " x ($depth + 1);
print "\"$k\":";
my $x = $r->{$k};
if(ref($x) =~ /ARRAY/)
{
print "[\n";
my $cnt = @{$x};
my $j = 0;
foreach my $o ( @{$x} )
{
json($o,$depth + 2);
if($j++ != $cnt-1)
{
#print " " x ($depth + 2);
print ",\n";
}
}
print "\n";
print " " x ($depth + 1);
print "]\n";
}
elsif(ref($x) =~ /HASH/) {
print "\n";
json($x,$depth+1);
}
else
{
print "\"$x\"";
}
if($i++ != $count-1)
{
print ",\n";
}
else
{
print "\n";
}
}
print " " x $depth;
print "}";
}
sub process {
my ($root, $tag,$kids, $depth) = @_;
my %att = %{$kids->[0]};
my $r;
$root->{_order} = [] unless(exists $root->{_order});
push @{$root->{_order}}, $tag;
if($root->{$tag}) {
$r = \%att;
if(ref($root->{$tag}) =~ /ARRAY/) {
push @{$root->{$tag}}, $r;
}
else
{
$root->{$tag} = [$root->{$tag}, $r];
}
}
else {
$r = $root->{$tag} = \%att;
}
$r->{_order} = [] unless(exists $r->{_order});
foreach my $k ( sort keys %att ) {
push @{$r->{_order}}, $k;
}
for(my $i = 1; $i < @{$kids} ; $i += 2)
{
if(ref($kids->[$i+1]))
{
process($r, $kids->[$i],$kids->[$i+1], $depth+1);
}
else {
my $text = $kids->[$i+1];
# $root->{_ctext} = $text;
#print "->$text\n";
}
}
return $root;
}
#print Dumper($x);
|