AnyData/Format/XML.pm untested

filter: Statementstmt 0.0% 0 / 601 Branchbran 0.0% 0 / 230 Conditioncond 0.0% 0 / 106 MC/DCmcdc 0.0% 0 / 66 Subroutinesub 0.0% 0 / 31 Podpod 0.0% 0 / 25 totaltotal 0.0% 0 / 1059 CC 116 SCAR 50.2
CC
116
Cov
0%
get_structure
462.0
read_dtd
272.0
get_structure_from_map
156.0
CRAP 151.1
1 ##################################################################
2 package AnyData::Format::XML;
3 ##################################################################
4 # an AnyData format parser for XML
5 # by Jeff Zucker <jeff@vpservices.com>
6 ##################################################################
7  
8 use strict;
9 use warnings;
10 use AnyData::Format::Base;
11 use AnyData::Storage::RAM;
12 use XML::Twig;
13 use vars qw( @ISA $DEBUG $VERSION);
14 @AnyData::Format::XML::ISA = qw( AnyData::Format::Base );
15  
16 $VERSION = '0.12';
17  
18 sub seek { 1 }
19 sub get_pos { 1 }
20 sub go_pos { 1 }
21  
22 sub new {
23 my $class = shift;
24 my $self = shift || {};
25 $self->{export_on_close} = 1;
26 $self->{slurp_mode} = 1;
27 if ($self->{col_names}) {
28 ## something goes here :-)
29 }
30 return bless $self, $class;
31 }
32  
33 sub storage_type { 'PassThru'; }
34  
35 sub truncate {
36 my $self = shift;
37 my $data = shift; # from SQL::Statement, ignored
38 for my $e( $self->{twig}->root->descendants ) {
39 next unless $e->gi eq 'delete__';
40 $e->delete;
41 }
42 undef $self->{last_before_delete};
43 }
44 sub push_row {
45 my $self = shift;
46 my @fields = @_;
47 my @ch = caller 3; # tied-hash
48 my @cd = caller 4; # DBD
49 my $hash_caller = $ch[3] || '';
50 my $dbd_caller = $cd[3] || '';
51 my @f = caller 4;
52 if ($dbd_caller =~ /SQL/ ) {
53 # DELETE | UPDATE | INSERT
54 if ( !$self->{last_before_delete} && $dbd_caller !~ /INSERT/ ) {
55 $self->{last_before_delete} = 1;
56 my @children = $self->{twig}->root->descendants;
57 for my $e(@children) {
58 next unless $e->path eq $self->{record_tag}->path;
59 next if $e->cmp($self->{record_tag}) == 0;
60 $e->set_gi("delete__")
61 }
62 }
63 #$self->{twig}->print; exit;
64 return $self->insert_record(\@fields);
65 }
66 $self->insert_record(\@fields);
67 }
68  
69 sub insert_record {
70 my $self = shift;
71 my $row = shift;
72 #print "@$row\n";
73 my $rect = $self->{record_tag};
74 my $col_structure = $self->{col_structure};
75 my @tags = @{$col_structure->{col_names}};
76 my @cols = @{$col_structure->{pretty_cols}};
77 my $is_atr = $col_structure->{amap};
78 my $p = $rect->path;
79 my $has_parent_atr;
80 for my $atr(keys %$is_atr) {
81 $has_parent_atr++ unless $atr =~ /^$p/;
82 }
83 my $col2tag = $col_structure->{col2tag} || {};
84  
85 my $elt= new XML::Twig::Elt($rect->gi); # CREATE ELEMENT
86 my $par;
87 my $par_name = $rect->parent->gi;
88 if ($has_parent_atr) {
89 $par = new XML::Twig::Elt($rect->parent->gi); # CREATE PARENT
90 }
91 my $rowhash;
92 @{$rowhash}{@cols} = @$row;
93 for my $i(0..$#cols) {
94 my $tag = $tags[$i];
95 my $col = $cols[$i];
96 my $value = $rowhash->{$col};
97 $tag ||= $col2tag->{$col};
98 my($path,$name) = $tag =~ m!^(.*)/([^/]*)$!;
99 if ($is_atr->{$tag} && defined $value) {
100 if ($tag =~ /^$p/) {
101 $elt->set_att($name,$value); # ADD ELT ATTRIBUTE
102 }
103 else {
104 $par->set_att($name,$value); # ADD PARENT ATTRIBUTE
105 }
106 }
107 elsif (defined $name && defined $value) {
108 my $kid= new XML::Twig::Elt($name); # CREATE CHILD
109 $kid->set_text($value); # ADD TEXT TO CHILD
110 $kid->paste('last_child',$elt); # PASTE CHILD INTO ELEMENT
111 }
112 }
113 if ($has_parent_atr) {
114 $elt->paste('last_child',$par); # PASTE ELT INTO PARENT
115 my $last = $rect->parent->parent->last_child($par_name);
116 $par->paste('after',$last); # PASTE PARENT INTO TREE
117 }
118 else {
119 my $last = $rect->parent->last_child($rect->gi);
120 $elt->paste('after',$last); # PASTE ELEMENT INTO TREE
121 }
122 #$self->{twig}->print;
123 }
124  
125 sub delete_record {
126 #my @calls = caller 3;
127 #my $call = $calls[3] || '';
128 #return if $call =~ /UPDATE/i;
129 #print "$call\n";
130 my $self = shift;
131 my $elt = $self->{prev_element};
132 my $rec = $self->{record_tag};
133 my $p = $rec->path;
134 my $new = $elt->prev_elt($rec->gi);
135 $elt = $new if $elt->path !~ /^$p/;
136 $self->{skip} = 1 if !$elt;
137 return undef unless $elt;
138 $elt->delete;
139 }
140  
141 sub DESTROY {
142 return;
143 print "XML DESTROYED";
144 my $self = shift;
145 if ( $self->{storage}->{fh}
146 && $self->{storage}->{open_mode} ne 'r'
147 ){
148 $self->export( $self->{storage} );
149 }
150 #undef $self->{twig};
151 #undef $self->{storage}->{fh};
152 }
153  
154 sub read_fields {
155 my $self = shift;
156 my $c = $self->{current_element};
157 return undef unless defined $c;
158 $c = $self->{current_element} = $c->next_elt($c->gi)
159 if $c->att('record_tag__');
160 $self->{prev_element} = $self->{current_element};
161 $self->{current_element} = $c->next_elt($c->gi) if $c;
162 return $self->process_element( $self->{prev_element} );
163 }
164  
165 sub process_element {
166 my $self = shift;
167 my $element = shift;
168 my @col_names = @{ $self->{col_structure}->{col_names} };
169 my @row;
170 my $parent = $element->parent;
171 my $values = { $element->path => $element->text };
172 my $par_ats = {};
173 $par_ats = $parent->atts if $parent;
174 my $elt_ats = $element->atts || {};
175 while( my($att_key,$att_val) = each %$par_ats) {
176 $values->{$parent->path.'/'.$att_key} = $att_val;
177 }
178 while( my($att_key,$att_val) = each %$elt_ats) {
179 $values->{$element->path.'/'.$att_key} = $att_val;
180 }
181 for my $kid($element->children) {
182 if ( defined $values->{$kid->path} ) {
183 if (!ref $values->{$kid->path}) {
184 $values->{$kid->path} = [ $values->{$kid->path} ] ;
185 }
186 push ( @{ $values->{$kid->path} }, $kid->text );
187 }
188 else {
189 $values->{$kid->path} = $kid->text;
190 }
191 }
192 for my $col(@col_names) {
193 if (ref $values->{$col}) {
194 @row = (@row,@{$values->{$col}});
195 }
196 else {
197 push @row, $values->{$col};
198 }
199  
200 }
201 # use Data::Dumper; print Dumper $values, Dumper \@row; exit;
202 return @row;
203 }
204  
205  
206 sub seek_first_record {
207 my $self = shift;
208 return unless $self->{twig} and $self->{twig}->root;
209 $self->{current_element} = $self->{record_tag};
210 }
211 sub push_names {
212 my $self = shift;
213 my $col_names = shift || $self->{col_names};
214 #my @c= caller 1; die $c[3]."!!!";
215 my $str = "<table>\n <row record_tag__='1'>\n";
216 #print "CREATING";
217 for (@$col_names) {
218 $str .= " <$_>dummy__</$_>\n";
219 }
220 $str .= " </row>\n</table>\n";
221 $str = $self->{template} if $self->{template};
222 if ( $self->{dtd} ) {
223 $str = $self->{dtd} if $self->{dtd};
224 my $root = $str;
225 $root =~ s/.*<!DOCTYPE\s+(\S+)\s+.*/$1/ms;
226 $str .= "\n\n<$root></$root>";
227 #die $str;
228 }
229 $self->get_data( $str );
230 return $self->{col_names};
231 }
232  
233 sub import {
234 my $self = shift;
235 my $data = shift;
236 my $storage = shift;
237 $self->init_parser($storage,$data);
238 return $self->get_data($data,$storage->{col_names});
239 }
240  
241 ####
242 # GET DATA FROM STRING
243 ###
244 sub init_parser {
245 my $self = shift;
246 my $storage = shift;
247 my $fh_or_str = shift;
248 return if 'co' =~ /$storage->{open_mode}/;
249 #print " INIT ...";
250 #print "HAS RECS\n" if $storage->{recs};
251 #print "HAS DATA\n" if ref $storage->{file} eq 'HASH';
252 $fh_or_str ||= $storage->{fh} if $storage->{fh};
253 $fh_or_str ||= $storage->{file}->{data} if ref $storage->{file} eq 'HASH';
254 $fh_or_str ||= $storage->{recs};
255 # $fh_or_str ||= join('',@$fh_or_str) if ref $fh_or_str eq 'ARRAY';
256 #print $fh_or_str; exit;
257 ###z $self->create_new_twig( $self->{col_names} );
258 my $rv = $self->get_data( $fh_or_str,$self->{col_names} );
259 return undef unless $rv;
260 $self->{current_element} = $self->{twig}->root;
261 $storage->{col_names} = $self->{col_names};
262 return 1;
263 }
264  
265 sub create_new_twig {
266 my $self = shift;
267 my $flags = $self;
268 my $root_tag = $flags->{root_tag};
269 my $depth_limit = $flags->{depth_limit};
270 # $flags->{twig_flags}->{TwigRoots} = {$root_tag=>'1'} if $root_tag;
271 # $flags->{twig_flags}->{KeepEncoding} ||= 1;
272 # $flags->{twig_flags}->{ProtocolEncoding} ||= 'ISO-8859-1';
273 $flags = $self->check_twig_options($flags);
274 $self->{twig}= new XML::Twig(%{$flags});
275 #$self->{twig}= new XML::Twig(%{$flags->{twig_flags}});
276 }
277  
278 sub read_dtd {
279 my $self = shift;
280 my $twig = shift;
281 #print Dumper $self->{dtd}; exit;
282 my $record_tag = $self->{record_tag};
283 my $col_names = $self->{col_names};
284 $col_names = $self->{dtd}->{elt_list};
285 my $newc;
286 my $colh;
287 #print Dumper $self->{dtd}; exit;
288 my $col_text;
289 for my $col(@$col_names) {
290 while (my($k,$v) = each %{ $self->{dtd}->{model} } ) {
291 if ($v =~ /(#P*CDATA)/ ) {
292 $col_text->{"$k$1"}++;
293 }
294 if ($v =~ /[(\s,]+$col[)\s,]+/ ) {
295 my @path = ($k,$col);
296 push @$newc, \@path;
297 $colh->{$col} = $k;
298 }
299 }
300 }
301 $col_names = [];
302 my $done;
303 my $nh;
304 while (!$done) {
305 $done = 1;
306 my $i;
307 for $i(0..scalar @$newc -1) {
308 my $cur = $newc->[$i]->[0];
309 # $cur =~ s"^.*/([^/]+)$"$1";
310 #print "$cur : ";
311 my $path = $colh->{ $cur };
312 my $p;
313 if ($path) {
314 $p = $newc->[$i]->[0] = $path . '/' . $newc->[$i]->[0];
315 # delete $colh->{$cur};
316 $nh->{$cur} = $p;
317 $done=0;
318 }
319 while (my($k,$v)=each %$nh) {
320 if ( $cur =~ m"^$k/(.*)") {
321 $newc->[$i]->[0] = $v . '/' . $1;
322 $done = 0;
323 }
324 }
325 }
326 }
327 #@array = grep(!$is_member{$_}++, @array);
328 my %is_member;
329 for my $row (@$newc) {
330 my $c = '/' . $row->[0] . '/' . $row->[1];
331 push @$col_names, $c if !$is_member{$c};
332 $is_member{$c}++;
333 }
334 # put in order by depth
335 @$col_names = sort {
336 my $x=$a;
337 my $y=$b;
338 $x =~ s"[^/]""g;; $x=length $x;
339 $y =~ s"[^/]""g;; $y=length $y;
340 $x <=> $y;
341 } @$col_names;
342 $record_tag ||= $col_names->[0];
343 $record_tag =~ s".*/([^/]+)$"$1";
344 # $record_tag = $twig->first_elt($record_tag)
345 # || die "Can't find column '$record_tag'!". $@;
346 #print $record_tag, Dumper $col_names; exit;
347 my %done;
348 for my $c(@$col_names) {
349 my @tags = split '/', $c;
350 shift @tags; # remove root
351 for my $i(0..$#tags) {
352 my $t = $tags[$i];
353 next if $done{$c.$t};
354 next unless $c =~ m"/$t$";
355 # print "$c:$t\n";
356 # next if $done{$t};
357 $done{$c.$t}++ ;
358 my $nxt = $twig->root->next_elt($t);
359 next if $nxt and $nxt->path =~ /^$c/;
360 next if $t eq $twig->root->gi;
361 my $p= $tags[$i-1];
362 my $pos = $twig->root->next_elt($p);
363 $pos ||= $twig->root;
364 my $e= new XML::Twig::Elt($t);
365 #if ($col_text->{$e->gi.'#PCDATA'}) {
366 # $e->append_pcdata("xxx");
367 #}
368 $e->paste('last_child',$pos);
369 # if ($col_text->{$e->gi.'#PCDATA'} ) {
370 # print $e->gi.'#PCDATA'."\n";
371 # $twig->root->next_elt($e->gi)->append_pcdata('x');
372 # }
373 }
374 }
375 my $atts;
376 while (my($k,$v)=each%{$self->{dtd}->{att}}) {
377 my $cur = $twig->root->next_elt($k);
378 next unless $cur;
379 while (my($k2,$v2)=each%{$v}) {
380 ### $cur->set_att($k2,"");
381 $atts->{$cur->path.'/'.$k2}=$k2;
382 #print "[".$cur->path.'/'.$k2."]";
383 }
384 }
385 $record_tag ||= $twig->root->first_child->gi;
386 $record_tag = $twig->root->next_elt($record_tag)
387 || die "Couldn't find column '$record_tag'!";
388 $newc = [];
389 my $found;
390 for my $org(@$col_names) {
391 my $x = $org;
392 $x =~ s".*/([^/]+)$"$1";
393 my $p =$record_tag->parent->path;
394 next unless $org =~ /^$p/;
395 #next unless $p =~ /^$_/;
396 while (my($k,$v)=each%$atts) {
397 next if $found->{$k};
398 if ( $k =~ m"$p/([^/]+)$"
399 or $k =~ m"$p/([^/]+/[^/]+)$"
400 ) {
401 #print "$k\n";
402 push @$newc, $k;
403 $found->{$k}++;
404 }
405 }
406 push @$newc, $org if $col_text->{$x.'#PCDATA'}
407 or $col_text->{$x.'#CDATA'};
408 }
409 #unshift @$newc, $record_tag->gi unless $found;
410 #die Dumper $newc;
411 #$twig->print; exit;
412  
413 my $elt = $twig->root;
414 if (!$self->{recs}) {
415 while ( $elt = $elt->next_elt ) {
416 $elt->set_att('xstruct__','1');
417 }
418 $record_tag->set_att('record_tag__','1');
419 }
420 #########
421 # COMMENT THIS TO SEE STRUCTURE TAGS
422 #
423 $self->{destroy}++;
424  
425 #print Dumper $record_tag->gi,$newc, $atts;
426 return( $record_tag,$newc, $atts);
427 #$twig->print; exit;
428 }
429  
430 sub get_structure {
431 my $self = shift;
432 my $twig = shift;
433 my $record_tag = $self->{record_tag};
434 # $record_tag ||= $self->{table_name};
435 my $col_names = $self->{col_names};
436 if ($self->{dtd}) {
437 return $self->read_dtd($twig)
438 }
439 $record_tag = $twig->first_elt($record_tag) if $record_tag;
440 $record_tag ||= $twig->root->first_child;
441 #print $record_tag->gi;
442 # if (!$record_tag) {
443 # $record_tag = $twig->root->first_child;
444 # if ( $record_tag
445 # and $record_tag->first_child
446 # and !$record_tag->contains_text
447 # and !$record_tag->first_child->contains_text
448 # ) {
449 # $record_tag = $record_tag->first_child;
450 # }
451 # }
452  
453 $self->{record_tag} = $record_tag;
454 if ($self->{create}) {
455 my $elt = $twig->root;
456 while ( $elt = $elt->next_elt ) {
457 $elt->set_att('xstruct__','1');
458 }
459 ###z# print "1";
460 $record_tag->set_att('record_tag__','1');
461 }
462 if ($col_names) {
463 @$col_names = map {
464 my $o = $_;
465 if ($o !~ m"/") {
466 $o = $twig->first_elt($o)->path;
467 }
468 $o;
469 } @$col_names;
470 }
471 else {
472 @$col_names = map {$_->path} $record_tag->descendants;
473 #die join "\n",@$col_names;
474 my $newcolz = [];
475 my %hashz;
476 for (@$col_names) {
477 next unless m"/#PCDATA|/#CDATA";
478 next if $hashz{$_};
479 push @$newcolz, $_;
480 $hashz{$_}++;
481 }
482 $col_names = $newcolz;
483 }
484 # my $oldcols = $col_names;
485 # $col_names = [];
486 #print join "\n", @$col_names; exit;
487 my $atts;
488 my @atts_to_check = ($record_tag,$record_tag->descendants);
489 #print $record_tag->gi,"\n";
490 if ($record_tag->parent and $record_tag->parent->parent) {
491  
492 unshift @atts_to_check, $record_tag->parent;
493 }
494 my $has_record_tag = 1 if $record_tag->att('record_tag__');
495 #print $has_record_tag ? 'HAS' : 'NONE';
496 #$twig->print;
497 #print $record_tag->path,"!\n";
498 # for (keys %{$record_tag->atts}) { print "$_#"; }
499 my @att_col;
500 for my $t(@atts_to_check) {
501 my $ats = $t->atts;
502 next unless $ats;
503 delete $ats->{record_tag__};
504 # push @$col_names, $t->path if $t->is_text;
505 # print $t->path . '/' . $_ for keys %$ats;
506 # unshift @$col_names, $t->path . '/' . $_ for keys %$ats;
507 push @att_col, $t->path . '/' . $_ for keys %$ats;
508 #unshift @$atts, $ats->{$_} for keys %$ats;
509 $atts->{$t->path . '/'. $_} = $_ for keys %$ats;
510 }
511 @$col_names = (@att_col,@$col_names);
512 @$col_names = map {s"/#P*CDATA""; $_} @$col_names;
513 #print join "\n",@$col_names;
514  
515 ###z# print 2;
516 # $record_tag->set_att('record_tag__','true');
517 $record_tag->set_att('record_tag__','true') if $record_tag->text =~/dummy__/;
518 # $record_tag->set_att('xstruct__','true') if $record_tag->text =~/dummy__/;
519 #
520 #if ($has_record_tag) { $twig->print; exit; }
521 return($record_tag,$col_names,$atts) if $has_record_tag;
522  
523 my $cols;
524 @$cols = map {$_} @$col_names;
525 my $elt= new XML::Twig::Elt($record_tag->gi);
526 for my $a(keys %$atts ) {
527 $a =~ s".*/([^/]+)$"$1";
528 next if $a eq 'record_tag__';
529 next unless $record_tag->att($a);
530 $elt->set_att($a,'');
531 }
532 for my $c(@$cols ) {
533 next if $atts->{$c};
534 next if $c =~ m"/#PCDATA";
535 $c =~ s"/#PCDATA"";
536 $c =~ s".*/([^/]+)$"$1";
537 my $e= new XML::Twig::Elt($c);
538 $e->paste('last_child',$elt);
539 }
540 my $par;
541 if ($record_tag->parent and $record_tag->parent->parent) {
542 $par= new XML::Twig::Elt($record_tag->parent->gi);
543 for my $a(keys %$atts ) {
544 $a =~ s".*/([^/]+)$"$1";
545 next unless $record_tag->parent->att($a);
546 $par->set_att($a,'');
547 }
548 ###z# print 3;
549 $elt->set_att('record_tag__','true');
550 $elt->paste('first_child',$par);
551 $par->paste('before',$record_tag->parent);
552 # $record_tag = $self->{record_tag} = $record_tag->parent->prev_sibling->first_child;
553 $record_tag ||= $self->{record_tag} = $record_tag->parent->prev_sibling->first_child;
554 }
555 else {
556 for my $a(keys %$atts ) {
557 $a =~ s".*/([^/]+)$"$1";
558 next unless $record_tag->att($a);
559 $elt->set_att($a,'');
560 }
561 ###z# print 4;
562 $record_tag ||= $self->{record_tag} = $record_tag->prev_sibling;
563 # $record_tag = $self->{record_tag} = $record_tag->prev_sibling;
564 }
565 $record_tag ||= $twig->root->first_child;
566 my $old = $record_tag->next_elt($record_tag->gi);
567 # $old->delete if $self->{create};
568 # $old->set_att('frump','foo') if $old;
569 $old->del_att('record_tag__') if $old;
570 #$twig->print;
571 #print "\n";
572 #$old->print if $old;
573 ##print "\n";
574 # my $par = $self->create_record;
575 # $self->{blank_element} = $par;
576 #printf "\n%s\n %s\n", $elt->path, "@$col_names";
577 @$col_names = map {s"/#PCDATA""; $_} @$col_names;
578 #$twig->print; print "\n\n";
579 #use Data::Dumper; print Dumper $record_tag->gi,$col_names,$atts;
580 return $record_tag,$col_names,$atts;
581 }
582  
583 sub check_twig_options {
584 my $flags = shift;
585 my $new_flags;
586 my %twig_opt = %XML::Twig::valid_option;
587 return $flags unless scalar (keys %twig_opt);
588 while (my($k,$v) = each %$flags) {
589 $new_flags->{$k} = $v if $twig_opt{$k};
590 }
591 return $new_flags;
592 }
593  
594 sub get_structure_from_map {
595 my $self = shift;
596 my $twig = shift;
597 my $col_map = shift;
598 my($amap,$map,$multi,$col_names,$pretty_cols,$col2tag);
599 for my $col(@$col_map) {
600 my($tag_name,$col_name) = ($col,$col);
601 ($tag_name,$col_name) = each %$col if ref $col eq 'HASH';
602 my($tname,$tparent) = ($tag_name,$tag_name);
603 if ($tname =~ m!(.*)/([^/]*)$! ) {
604 $tparent = $1;
605 $tname = $2;
606 $tparent =~ s!.*/([^/]*)$!$1!;
607 }
608 my $tag = $twig->first_elt($tname);
609 $tag_name=$tag->path if $tag;
610 if (!$tag) {
611 my $new_tag = $twig->first_elt($tparent);
612 # die "No such element '$tname'!" unless $tag;
613 if (!$new_tag) {
614 $tag_name = $tname;
615 }
616 else {
617 $tag_name=$new_tag->path . '/' . $tname;
618 }
619 $amap->{$tag_name}++;
620 }
621 if (ref $col_name eq 'ARRAY') {
622 for my $col2(@$col_name) {
623 $col2tag->{$col2} = $tag_name;
624 $multi->{$tag_name}++;
625 push @$pretty_cols, $col2;
626 }
627 }
628 push @$col_names, $tag_name;
629 push @$pretty_cols, $col_name unless ref $col_name eq 'ARRAY';
630 $map->{$tag_name} = $col_name;
631 }
632 my $record_tag;
633 my $record_tag_path = '';
634 for my $col(@$col_names) {
635 my($rt) = $col =~ m!(.*)/[^/]*$!;
636 next unless $rt;
637 $record_tag_path = $rt if length $rt > length $record_tag_path;
638 }
639 my @children = $twig->root->descendants;
640 for my $e(@children) {
641 next unless $e->path eq $record_tag_path;
642 $record_tag = $e;
643 last;
644 }
645 if (!$record_tag) {
646 $record_tag = $twig->root->first_child;
647 my $p = $record_tag->path;
648 @$col_names = map {$p.'/'.$_}@$col_names;
649 # use Data::Dumper; print Dumper $amap;
650 my $newmap;
651 $newmap->{ $p.'/'.$_ }++ for keys %{$amap};
652 $amap = $newmap;
653 $newmap = {};
654 $newmap->{ $p.'/'.$_ } = $map->{$_} for keys %{$map};
655 $map = $newmap;
656 }
657 ##
658 #=pod
659 #paste into parent record_tag__
660 # my $rt_atts = $record_tag->atts;
661 # if (!$rt_atts->{record_tag__}) {
662 # my $new_rt = $record_tag->copy;
663 # $new_rt->set_att('record_tag__','1');
664 # $new_rt->set_att('xstruct__','1');
665 # $new_rt->paste('first_child',$record_tag->parent);
666 # $record_tag = $new_rt;
667 # }
668 #=cut
669 my $col_structure = {
670 amap => $amap,
671 map => $map,
672 multi => $multi,
673 col_names => $col_names,
674 pretty_cols => $pretty_cols,
675 col2tag => $col2tag,
676 };
677 # print $record_tag->path, "\n";
678 # use Data::Dumper; print Dumper $col_structure;
679 # exit;
680 return $record_tag, $col_structure;
681 }
682  
683 sub get_data {
684 my $self = shift;
685 my $fh_or_str = shift;
686 my $url = $self->{url};
687 if ( $url ) {
688 $fh_or_str = AnyData::Storage::RAM::get_remote_data({},$url);
689 }
690 return if( ! defined( $fh_or_str ) );
691 my $col_names = shift || [];
692 $col_names = []; #### IGNORE USER COLUMN NAMES FOR NOW
693 my $flags;
694 while (my($k,$v)=each %$self) {
695 $flags->{$k}=$v;
696 }
697 my $root_tag = $flags->{root_tag};
698 my $depth_limit = $flags->{depth_limit};
699 my $supplied_col_names = $flags->{col_names};
700 my $have_col_names = 1 if $supplied_col_names;
701 my $pretty_col_names = $supplied_col_names;
702 my $col_structure = $self->{col_structure};
703 undef $col_structure unless $col_structure->{col_names}
704 and scalar @{$col_structure->{col_names}};
705 my %multi;
706 my %map;
707 my %amap;
708 $flags->{LoadDTD} = 1;
709 $flags->{TwigRoots} = {$root_tag=>'1'} if $root_tag;
710 #
711 # DEFAULTS : KeepEncoding OFF to mirror XML::Twig
712 # ProtocolEncoding 'ISO-8859-1'
713 #
714 # $flags->{KeepEncoding} ||= 1;
715 #
716 $flags->{ProtocolEncoding} ||= 'ISO-8859-1';
717 #use Data::Dumper; die Dumper $flags;
718 $flags = check_twig_options($flags);
719  
720 my $twig= new XML::Twig(%{$flags});
721 my $success = $twig->safe_parse($fh_or_str);
722 $self->{errstr} = $@ unless $success;
723 die $self->{errstr} if $self->{errstr};
724 return undef unless $success;
725 $self->{dtd} = $twig->dtd;
726 my $root = $twig->first_elt($root_tag) || $twig->root;
727 my $name = $root->path;
728 my $element= $twig->root;
729 my($record_tag,$colZ,$atts);
730  
731 my $col_map = $self->{col_map};
732 if ($col_map) {
733 ($record_tag,$col_structure) =
734 $self->get_structure_from_map($twig,$col_map);
735 }
736 else {
737 ($record_tag,$colZ,$atts) = $self->get_structure($twig);
738 if (!$col_structure) {
739 $have_col_names++;
740 $col_structure = build_column_names($colZ,$root,$root_tag,$colZ);
741 $col_structure->{amap} = $atts;
742 }
743 }
744  
745 # CREATE A DUMMY RECORD TAG
746 #
747 my $rt_atts = $record_tag->atts;
748 if (!$rt_atts->{record_tag__}) {
749 my $new_rt = $record_tag->copy;
750 $new_rt->set_att('record_tag__','1');
751 $new_rt->set_att('xstruct__','1');
752 $new_rt->paste('first_child',$record_tag->parent);
753 $record_tag = $new_rt;
754 }
755  
756 # $twig->print;
757 # use Data::Dumper; print Dumper $col_structure;
758 # print $self->{record_tag}->path;
759  
760 $self->{record_tag} = $record_tag;
761 $self->{twig} = $twig;
762 $self->{col_names} = $col_structure->{pretty_cols};
763 $self->{col_structure} = $col_structure;
764 return 1;
765 }
766  
767  
768 ###############################################################
769 # MAP A ROW HASH ONTO A COLUMN NAMES ARRAY
770 ###############################################################
771 sub rowhash_to_array {
772 my $row = shift;
773 my $col_structure = shift;
774 #die Dumper $col_structure;
775 my $col_names = $col_structure->{col_names};
776 my %map = %{ $col_structure->{map} } if $col_structure->{map};
777 my %multi = %{ $col_structure->{multi} } if $col_structure->{multi};
778 my $pretty_col_names = $col_structure->{pretty_cols} if $col_structure->{pretty_cols};
779 my @newvals;
780 my %visited;
781 for my $coln(@$col_names) {
782 my $tag = $map{$coln};
783 #next unless $tag;
784 if (!$multi{$tag}) {
785 $row->{$tag} ? push @newvals, $row->{$tag} : push @newvals, undef;
786 }
787 else {
788 if (!$visited{$tag}) {
789 $visited{$tag}++;
790 my @multi_col = ref $row->{$tag} eq 'ARRAY'
791 ? @{$row->{$tag}}
792 : ($row->{$tag});
793 push @multi_col,undef unless scalar @multi_col;
794 my $dif = ($multi{$tag}) - (scalar @multi_col);
795 push @multi_col,undef for 0 .. $dif;
796 push @newvals,$_ for @multi_col;
797 }
798 }
799 }
800 return( \@newvals );
801 }
802 ###############################################################
803 # BUILD A COLUMN NAMES LIST IF NONE HAS BEEN BUILT YET
804 ###############################################################
805 sub build_column_names {
806 my $tags = shift;
807 my $root = shift;
808 my $root_tag = shift;
809 my $col_names = shift || [];
810 my %multi;
811 my %map;
812 for my $col(@$col_names) {
813 $multi{$col}++;
814 }
815 my %num;
816 my $newcolz;
817 for my $col(@$col_names) {
818 if ($multi{$col} <2) {
819 push @$newcolz, $col;
820 $map{$col}=$col;
821 next;
822 }
823 $num{$col}++;
824 push @$newcolz, $col.$num{$col};
825 $map{$col.$num{$col}}=$col;
826 }
827 $col_names = $newcolz;
828 # REMOVE AS MUCH OF THE PATH AS POSS., KEEPING NAMES UNIQUE
829 #
830 my $prefix = $root->gi;
831 $prefix .= "/$root_tag" if $root_tag;
832 my $pretty_col_names;
833 die "No Column Names!" unless$col_names;
834 @$pretty_col_names = @$col_names;
835 @$pretty_col_names = map {$_ =~ s"^/$prefix/"";$_} @$pretty_col_names;
836 my %is_member;
837 my @newcols;
838 for my $col(@$pretty_col_names) {
839 my $newc = $col;
840 $newc =~ s".*/([^/]*)$"$1";
841 if ($is_member{$newc}) {
842 $newc = $col;
843 $newc =~ s"[^/]*/(.*)"$1";
844 }
845 push @newcols, $is_member{$newc} ? $col : $newc;
846 $is_member{$newc}=1;
847 }
848 @$pretty_col_names = @newcols;
849 @$pretty_col_names = map {s"/"_"g;$_} @$pretty_col_names;
850 for (keys %multi) {
851 $multi{$_} = $multi{$_} -1;
852 delete $multi{$_} unless $multi{$_};
853 }
854 my $col_structure = {
855 col_names => $col_names,
856 map => \%map,
857 multi => \%multi,
858 pretty_cols => $pretty_col_names,
859 };
860 #print Dumper $col_structure;
861 return( $col_structure );
862 }
863 ###############################################################
864  
865 sub export {
866 my $self = shift;
867 my $storage = shift;
868 #z my $format = shift;
869 my $file = shift;
870 my $flags = shift || {};
871 #$self->{twig}->print;
872 if (
873 ( $storage and $file and !$storage->{fh} )
874 ) {
875 $storage->{file_name} = $file;
876 $storage->{fh} = $storage->open_local_file($file,'o');
877 }
878 return unless $self->{twig};
879 #$self->{twig}->print;
880 $self->{twig}->set_pretty_print($flags->{pretty_print}) if $flags->{pretty_print};
881 #$self->{twig}->print; print "\n\n";
882 #$self->{twig}->finish_print;
883 my $fh = $storage->{fh} if $storage;
884 my $r = $self->{twig}->root->gi;
885 my $str = $self->{outside_of_tree} || '';
886 my $rectag = $self->{record_tag};
887 # $self->{twig}->first_elt($self->{record_tag}->gi)->delete;
888 my $elt= $self->{twig}->root;
889 # $self->{destroy}= 1;
890 #print "FOO";
891 if ( $self->{destroy}) {
892 for my $e($elt->descendants) {
893 if ( $e->att('xstruct__') ) {
894 $e->del_att('xstruct__');
895 # next unless defined $e->next_elt($e->gi);
896 $e->delete;
897 #next;
898 }
899 }
900 }
901 $elt= $self->{twig}->root;
902 while( $elt= $elt->next_elt ){
903 #for (keys %{$elt->atts}) { print "$_#"; }
904 my $del_parent;
905 # $elt->delete if $elt->text =~ /x/ and $elt->is_text;
906 if ($elt->children == 0 ) {
907 # $elt->delete;
908 next;
909 }
910 next if !$elt->att('record_tag__');
911 for ($elt->children) {
912 $_->delete;
913 }
914 if ($elt->parent and $elt->parent->children < 2) {
915 $del_parent++;
916 }
917 $elt->parent->delete if $del_parent;
918 $elt->delete;
919 }
920 ###z
921 # $str = defined $fh ? $self->{twig}->print($fh)
922 # : $self->{twig}->sprint();
923 if($file and defined $fh ){ $str = $self->{twig}->print($fh) }
924 else {$str = $self->{twig}->sprint();}
925 undef $storage->{fh};
926 return $str;
927 }
928  
929 1;
930  
931 =head1 NAME
932  
933 AnyData::Format::XML - tiedhash and DBI access to XML
934  
935 =head1 SYNOPSIS
936  
937 # access XML data via a multidimensional tied hash
938 # see AnyData.pod for full details
939 #
940 use AnyData;
941 my $table = adTie( 'XML', $file, $mode, $flags );
942  
943 OR
944  
945 # convert data to and from XML
946 # see AnyData.pod for full details
947 #
948 use AnyData;
949 adConvert( 'XML', $file1, $any_other_format, $file2, $flags );
950 adConvert( $any_other_format, $file1, 'XML', $file2, $flags );
951  
952 OR
953  
954 # access the data via DBI and SQL
955 # see DBD::AnyData.pod for full details
956 #
957 use DBI;
958 my $dbh = DBI->connect( 'dbi:AnyData' );
959 $dbh->func('mytable','XML',$file,$flags,'ad_catalog');
960  
961 See below for a description of the optional flags that apply
962 to all of these examples.
963  
964 =head1 DESCRIPTION
965  
966 This module allows you to create, search, modify and/or convert XML data
967 and files by treating them as databases without having to actually
968 create separate database files. The data can
969 be accessed via a multidimensional tiedhash using AnyData.pm or via DBI
970 and SQL commands using DBD::AnyData.pm. See those modules for
971 complete details of usage.
972  
973 The module is built on top of Michel Rodriguez's excellent XML::Twig which
974 means that the AnyData interfaces can now include information from DTDs,
975 be smarter about inferring data structure, reduce memory consumption on
976 huge files, and provide access to many powerful features of XML::Twig and
977 XML::Parser on which it is based.
978  
979 Importing options allow you to import/access/modify XML of almost any length or complexity. This includes the ability to access different subtrees as separate or joined databases.
980  
981 Exporting and converting options allow you to take data from almost any source (a perl array, any DBI database, etc.) and output it as an XML file. You can control the formatting of the resulting XML either by supplying a DTD listing things like nesting of tags and which columns should be output as attributes and/or you can use XML::Twig pretty_print settings to generate half a dozen different levels of compactness or whitespace in how the XML looks.
982  
983 The documentation below outlines the special flags that can be used
984 in either of the interfaces to fine-tune how the XML is treated.
985  
986 The flags listed below define the relationship between tags and
987 attributes in the XML document and columns in the resulting database.
988 In many cases, you can simply accept the defaults and the database
989 will be built automatically. However, you can also fine tune the
990 generation of the database by specifying which tags and attributes
991 you are interested in and their relationship with database columns.
992  
993 =head1 USAGE
994  
995 =head2 Prerequisites
996  
997 To use the tied hash interface, you will need
998  
999 AnyData
1000 XML::Twig
1001 XML::Parser
1002  
1003 To use the DBI/SQL interface, you will need those, and also
1004  
1005 DBI
1006 DBD::AnyData
1007  
1008 =head2 Required flags ( none )
1009  
1010 If no flags are specified, then the module determines the database
1011 structure from examining the file or data itself, making use of the DTD if there is one, otherwise scanning the first child of the XML tree for structural information.
1012  
1013 =head2 Optional flags
1014  
1015 If the default behavior is not sufficient, you may either specify a
1016 "record_tag" which will be used to define column names, or you can define an
1017 entire tag-to-column mapping.
1018  
1019  
1020 For simple XML, no flags are necessary:
1021  
1022 <table>
1023 <row row_id="1"><name>Joe</name><location>Seattle</location></row>
1024 <row row_id="2"><name>Sue</name><location>Portland</location></row>
1025 </table>
1026  
1027 The record_tag will default to the first child, namely "row". The column
1028 names will be generated from the attributes of the record tag and all of
1029 the tags included under the record tag, so the column names in this
1030 example will be "row_id","name","location".
1031  
1032 If the record_tag is not the first child, you will need to specify it. For example:
1033  
1034 <db>
1035 <table table_id="1">
1036 <row row_id="1"><name>Joe</name><location>Seattle</location></row>
1037 <row row_id="2"><name>Sue</name><location>Portland</location></row>
1038 </table>
1039 <table table_id="2">
1040 <row row_id="1"><name>Bob</name><location>Boise</location></row>
1041 <row row_id="2"><name>Bev</name><location>Billings</location></row>
1042 </table>
1043 </db>
1044  
1045 In this case you will need to specify "row" as the record_tag since it is not the first child of the tree. The column names will be generated from the attributes of row's parent (if the parent is not the root), from row's attributes
1046 and sub tags, i.e. "table_id","row_id","name","location".
1047  
1048 In some cases you will need to specify an entire tag-to-column mapping. For example, if you want to use a different name for the database column than is used in the XML (especially if the XML tag is not a valid SQL column name). You'd also need to specify a mapping if there are two tags with the same name in different places in the XML tree.
1049  
1050 The column mapping is a reference to an array of column definitions. A column definition is either a simple name of a tag, or a hash reference with the key containing the full path of the XML tag and the value containing the desired column name alias.
1051  
1052 For example:
1053  
1054 col_map => [ 'part_id', 'part_name', 'availability' ];
1055  
1056 That will find the first three tags with those names and create the database using the same names for the tags.
1057  
1058 Or:
1059  
1060 col_map => [
1061 { '/parts/shop/id' => 'shop_id'},
1062 { '/parts/shop/part/id' => 'part_id'},
1063 { '/parts/shop/part/name' => 'part_name'},
1064 ];
1065  
1066 That would find the three tags referenced on the left and create a database with the three column names referenced on the right.
1067  
1068 When exporting XML, you can specify a DTD to control the output. For example, if you import a table from CSV or from an Array, you can output as XML and specify which of the columns become tags and which become attributes and also specify the nesting of the tags in your DTD.
1069  
1070 The XML format parser is built on top of Michel Rodriguez's excellent XML::Twig which is itself based on XML::Parser. Parameters to either of those modules may be passed in the flags for adTie() and the other commands including the "prettyPrint" flag to specify how the output XML is displayed and things like ProtocolEncoding. ProtocolEncoding defaults to 'ISO-8859-1', all other flags keep the defaults of XML::Twig and XML::Parser. See the documentation of those modules for details;
1071  
1072 CAUTION: Unlike other formats, the XML format does not save changes to
1073 the file as they are entered, but only saves the changes when you explicitly
1074 request them to be saved with the adExport() command.
1075  
1076 =head1 AUTHOR & COPYRIGHT
1077  
1078 copyright 2000, Jeff Zucker <jeff@vpservices.com>
1079 all rights reserved
1080  
1081 =cut