Thread Perl & XML: Tabelle in 2-dimensionales Array umwandeln (4 answers)
Opened by pktm at 2011-02-28 21:33

topeg
 2011-02-28 22:26
#146120 #146120
User since
2006-07-10
2611 Artikel
BenutzerIn

user image
So kann man es machen:

more (11.8kb):
Code (perl): (dl )
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
#!/usr/bin/perl
use strict;
use warnings;
use XML::Parser;
use Data::Dumper;

my $string = qq~
<root>
        <row no="0">
                <col no="0">0.0</col>
                <col no="1">1.0</col>
                <col no="2">2.0</col>
                <col no="3">3.0</col>
        </row>
        <row no="1">
                <col no="0">4.0</col>
                <col no="1">5.0</col>
                <col no="2">6.0</col>
                <col no="3">7.0</col>
        </row>
        <row no="2">
                <col no="0">8.0</col>
                <col no="1">9.0</col>
                <col no="2">10.0</col>
                <col no="3">11.0</col>
        </row>
        <row no="3">
                <col no="0">12.0</col>
                <col no="1">13.0</col>
                <col no="2">14.0</col>
                <col no="3">15.0</col>
        </row>
</root>
~;

my $matrix=[];

my $ref_row;
my $ref_col;

my $parser = XML::Parser->new(Handlers => {
  Start => sub{
    my $parser=shift;
    my $name=shift;
    my $opts={@_};
    if($name eq 'row')
    {
      $ref_row=[];
      $matrix->[$opts->{no}]=$ref_row;
      $ref_col=undef;
    }
    elsif($name eq 'col' && $ref_row)
    { $ref_col=\$ref_row->[$opts->{no}]; }
  },
  Char => sub{
    my $parser=shift;
    my $string=shift;
    if($ref_col)
    {
      $$ref_col=$string;
      $ref_col=undef;
    }
  }});

$parser->parse($string);

print Dumper($matrix);


Das muss man natürlich verfeinern wenn es komplexer werden soll.

View full thread Perl & XML: Tabelle in 2-dimensionales Array umwandeln