-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathSimple.pm
More file actions
executable file
·3284 lines (2435 loc) · 94.8 KB
/
Copy pathSimple.pm
File metadata and controls
executable file
·3284 lines (2435 loc) · 94.8 KB
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# $Id: Simple.pm,v 1.40 2007/08/15 10:36:48 grantm Exp $
package XML::Simple;
=head1 NAME
XML::Simple - Easy API to maintain XML (esp config files)
=head1 SYNOPSIS
use XML::Simple;
my $ref = XMLin([<xml file or string>] [, <options>]);
my $xml = XMLout($hashref [, <options>]);
Or the object oriented way:
require XML::Simple;
my $xs = XML::Simple->new(options);
my $ref = $xs->XMLin([<xml file or string>] [, <options>]);
my $xml = $xs->XMLout($hashref [, <options>]);
(or see L<"SAX SUPPORT"> for 'the SAX way').
To catch common errors:
use XML::Simple qw(:strict);
(see L<"STRICT MODE"> for more details).
=cut
# See after __END__ for more POD documentation
# Load essentials here, other modules loaded on demand later
use strict;
use Carp;
require Exporter;
##############################################################################
# Define some constants
#
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK $PREFERRED_PARSER);
@ISA = qw(Exporter);
@EXPORT = qw(XMLin XMLout);
@EXPORT_OK = qw(xml_in xml_out);
$VERSION = '2.18';
$PREFERRED_PARSER = undef;
my $StrictMode = 0;
my @KnownOptIn = qw(keyattr keeproot forcecontent contentkey noattr
searchpath forcearray cache suppressempty parseropts
grouptags nsexpand datahandler varattr variables
normalisespace normalizespace valueattr);
my @KnownOptOut = qw(keyattr keeproot contentkey noattr
rootname xmldecl outputfile noescape suppressempty
grouptags nsexpand handler noindent attrindent nosort
valueattr numericescape);
my @DefKeyAttr = qw(name key id);
my $DefRootName = qq(opt);
my $DefContentKey = qq(content);
my $DefXmlDecl = qq(<?xml version='1.0' standalone='yes'?>);
my $xmlns_ns = 'http://www.w3.org/2000/xmlns/';
my $bad_def_ns_jcn = '{' . $xmlns_ns . '}'; # LibXML::SAX workaround
##############################################################################
# Globals for use by caching routines
#
my %MemShareCache = ();
my %MemCopyCache = ();
##############################################################################
# Wrapper for Exporter - handles ':strict'
#
sub import {
# Handle the :strict tag
$StrictMode = 1 if grep(/^:strict$/, @_);
# Pass everything else to Exporter.pm
@_ = grep(!/^:strict$/, @_);
goto &Exporter::import;
}
##############################################################################
# Constructor for optional object interface.
#
sub new {
my $class = shift;
if(@_ % 2) {
croak "Default options must be name=>value pairs (odd number supplied)";
}
my %known_opt;
@known_opt{@KnownOptIn, @KnownOptOut} = (undef) x 100;
my %raw_opt = @_;
my %def_opt;
while(my($key, $val) = each %raw_opt) {
my $lkey = lc($key);
$lkey =~ s/_//g;
croak "Unrecognised option: $key" unless(exists($known_opt{$lkey}));
$def_opt{$lkey} = $val;
}
my $self = { def_opt => \%def_opt };
return(bless($self, $class));
}
##############################################################################
# Sub: _get_object()
#
# Helper routine called from XMLin() and XMLout() to create an object if none
# was provided. Note, this routine does mess with the caller's @_ array.
#
sub _get_object {
my $self;
if($_[0] and UNIVERSAL::isa($_[0], 'XML::Simple')) {
$self = shift;
}
else {
$self = XML::Simple->new();
}
return $self;
}
##############################################################################
# Sub/Method: XMLin()
#
# Exported routine for slurping XML into a hashref - see pod for info.
#
# May be called as object method or as a plain function.
#
# Expects one arg for the source XML, optionally followed by a number of
# name => value option pairs.
#
sub XMLin {
my $self = &_get_object; # note, @_ is passed implicitly
my $target = shift;
# Work out whether to parse a string, a file or a filehandle
if(not defined $target) {
return $self->parse_file(undef, @_);
}
elsif($target eq '-') {
local($/) = undef;
$target = <STDIN>;
return $self->parse_string(\$target, @_);
}
elsif(my $type = ref($target)) {
if($type eq 'SCALAR') {
return $self->parse_string($target, @_);
}
else {
return $self->parse_fh($target, @_);
}
}
elsif($target =~ m{<.*?>}s) {
return $self->parse_string(\$target, @_);
}
else {
return $self->parse_file($target, @_);
}
}
##############################################################################
# Sub/Method: parse_file()
#
# Same as XMLin, but only parses from a named file.
#
sub parse_file {
my $self = &_get_object; # note, @_ is passed implicitly
my $filename = shift;
$self->handle_options('in', @_);
$filename = $self->default_config_file if not defined $filename;
$filename = $self->find_xml_file($filename, @{$self->{opt}->{searchpath}});
# Check cache for previous parse
if($self->{opt}->{cache}) {
foreach my $scheme (@{$self->{opt}->{cache}}) {
my $method = 'cache_read_' . $scheme;
my $opt = $self->$method($filename);
return($opt) if($opt);
}
}
my $ref = $self->build_simple_tree($filename, undef);
if($self->{opt}->{cache}) {
my $method = 'cache_write_' . $self->{opt}->{cache}->[0];
$self->$method($ref, $filename);
}
return $ref;
}
##############################################################################
# Sub/Method: parse_fh()
#
# Same as XMLin, but only parses from a filehandle.
#
sub parse_fh {
my $self = &_get_object; # note, @_ is passed implicitly
my $fh = shift;
croak "Can't use " . (defined $fh ? qq{string ("$fh")} : 'undef') .
" as a filehandle" unless ref $fh;
$self->handle_options('in', @_);
return $self->build_simple_tree(undef, $fh);
}
##############################################################################
# Sub/Method: parse_string()
#
# Same as XMLin, but only parses from a string or a reference to a string.
#
sub parse_string {
my $self = &_get_object; # note, @_ is passed implicitly
my $string = shift;
$self->handle_options('in', @_);
return $self->build_simple_tree(undef, ref $string ? $string : \$string);
}
##############################################################################
# Method: default_config_file()
#
# Returns the name of the XML file to parse if no filename (or XML string)
# was provided.
#
sub default_config_file {
my $self = shift;
require File::Basename;
my($basename, $script_dir, $ext) = File::Basename::fileparse($0, '\.[^\.]+');
# Add script directory to searchpath
if($script_dir) {
unshift(@{$self->{opt}->{searchpath}}, $script_dir);
}
return $basename . '.xml';
}
##############################################################################
# Method: build_simple_tree()
#
# Builds a 'tree' data structure as provided by XML::Parser and then
# 'simplifies' it as specified by the various options in effect.
#
sub build_simple_tree {
my $self = shift;
my $tree = $self->build_tree(@_);
return $self->{opt}->{keeproot}
? $self->collapse({}, @$tree)
: $self->collapse(@{$tree->[1]});
}
##############################################################################
# Method: build_tree()
#
# This routine will be called if there is no suitable pre-parsed tree in a
# cache. It parses the XML and returns an XML::Parser 'Tree' style data
# structure (summarised in the comments for the collapse() routine below).
#
# XML::Simple requires the services of another module that knows how to parse
# XML. If XML::SAX is installed, the default SAX parser will be used,
# otherwise XML::Parser will be used.
#
# This routine expects to be passed a filename as argument 1 or a 'string' as
# argument 2. The 'string' might be a string of XML (passed by reference to
# save memory) or it might be a reference to an IO::Handle. (This
# non-intuitive mess results in part from the way XML::Parser works but that's
# really no excuse).
#
sub build_tree {
my $self = shift;
my $filename = shift;
my $string = shift;
my $preferred_parser = $PREFERRED_PARSER;
unless(defined($preferred_parser)) {
$preferred_parser = $ENV{XML_SIMPLE_PREFERRED_PARSER} || '';
}
if($preferred_parser eq 'XML::Parser') {
return($self->build_tree_xml_parser($filename, $string));
}
eval { require XML::SAX; }; # We didn't need it until now
if($@) { # No XML::SAX - fall back to XML::Parser
if($preferred_parser) { # unless a SAX parser was expressly requested
croak "XMLin() could not load XML::SAX";
}
return($self->build_tree_xml_parser($filename, $string));
}
$XML::SAX::ParserPackage = $preferred_parser if($preferred_parser);
my $sp = XML::SAX::ParserFactory->parser(Handler => $self);
$self->{nocollapse} = 1;
my($tree);
if($filename) {
$tree = $sp->parse_uri($filename);
}
else {
if(ref($string) && ref($string) ne 'SCALAR') {
$tree = $sp->parse_file($string);
}
else {
$tree = $sp->parse_string($$string);
}
}
return($tree);
}
##############################################################################
# Method: build_tree_xml_parser()
#
# This routine will be called if XML::SAX is not installed, or if XML::Parser
# was specifically requested. It takes the same arguments as build_tree() and
# returns the same data structure (XML::Parser 'Tree' style).
#
sub build_tree_xml_parser {
my $self = shift;
my $filename = shift;
my $string = shift;
eval {
local($^W) = 0; # Suppress warning from Expat.pm re File::Spec::load()
require XML::Parser; # We didn't need it until now
};
if($@) {
croak "XMLin() requires either XML::SAX or XML::Parser";
}
if($self->{opt}->{nsexpand}) {
carp "'nsexpand' option requires XML::SAX";
}
my $xp = XML::Parser->new(Style => 'Tree', @{$self->{opt}->{parseropts}});
my($tree);
if($filename) {
# $tree = $xp->parsefile($filename); # Changed due to prob w/mod_perl
local(*XML_FILE);
open(XML_FILE, '<', $filename) || croak qq($filename - $!);
$tree = $xp->parse(*XML_FILE);
close(XML_FILE);
}
else {
$tree = $xp->parse($$string);
}
return($tree);
}
##############################################################################
# Method: cache_write_storable()
#
# Wrapper routine for invoking Storable::nstore() to cache a parsed data
# structure.
#
sub cache_write_storable {
my($self, $data, $filename) = @_;
my $cachefile = $self->storable_filename($filename);
require Storable; # We didn't need it until now
if ('VMS' eq $^O) {
Storable::nstore($data, $cachefile);
}
else {
# If the following line fails for you, your Storable.pm is old - upgrade
Storable::lock_nstore($data, $cachefile);
}
}
##############################################################################
# Method: cache_read_storable()
#
# Wrapper routine for invoking Storable::retrieve() to read a cached parsed
# data structure. Only returns cached data if the cache file exists and is
# newer than the source XML file.
#
sub cache_read_storable {
my($self, $filename) = @_;
my $cachefile = $self->storable_filename($filename);
return unless(-r $cachefile);
return unless((stat($cachefile))[9] > (stat($filename))[9]);
require Storable; # We didn't need it until now
if ('VMS' eq $^O) {
return(Storable::retrieve($cachefile));
}
else {
return(Storable::lock_retrieve($cachefile));
}
}
##############################################################################
# Method: storable_filename()
#
# Translates the supplied source XML filename into a filename for the storable
# cached data. A '.stor' suffix is added after stripping an optional '.xml'
# suffix.
#
sub storable_filename {
my($self, $cachefile) = @_;
$cachefile =~ s{(\.xml)?$}{.stor};
return $cachefile;
}
##############################################################################
# Method: cache_write_memshare()
#
# Takes the supplied data structure reference and stores it away in a global
# hash structure.
#
sub cache_write_memshare {
my($self, $data, $filename) = @_;
$MemShareCache{$filename} = [time(), $data];
}
##############################################################################
# Method: cache_read_memshare()
#
# Takes a filename and looks in a global hash for a cached parsed version.
#
sub cache_read_memshare {
my($self, $filename) = @_;
return unless($MemShareCache{$filename});
return unless($MemShareCache{$filename}->[0] > (stat($filename))[9]);
return($MemShareCache{$filename}->[1]);
}
##############################################################################
# Method: cache_write_memcopy()
#
# Takes the supplied data structure and stores a copy of it in a global hash
# structure.
#
sub cache_write_memcopy {
my($self, $data, $filename) = @_;
require Storable; # We didn't need it until now
$MemCopyCache{$filename} = [time(), Storable::dclone($data)];
}
##############################################################################
# Method: cache_read_memcopy()
#
# Takes a filename and looks in a global hash for a cached parsed version.
# Returns a reference to a copy of that data structure.
#
sub cache_read_memcopy {
my($self, $filename) = @_;
return unless($MemCopyCache{$filename});
return unless($MemCopyCache{$filename}->[0] > (stat($filename))[9]);
return(Storable::dclone($MemCopyCache{$filename}->[1]));
}
##############################################################################
# Sub/Method: XMLout()
#
# Exported routine for 'unslurping' a data structure out to XML.
#
# Expects a reference to a data structure and an optional list of option
# name => value pairs.
#
sub XMLout {
my $self = &_get_object; # note, @_ is passed implicitly
croak "XMLout() requires at least one argument" unless(@_);
my $ref = shift;
$self->handle_options('out', @_);
# If namespace expansion is set, XML::NamespaceSupport is required
if($self->{opt}->{nsexpand}) {
require XML::NamespaceSupport;
$self->{nsup} = XML::NamespaceSupport->new();
$self->{ns_prefix} = 'aaa';
}
# Wrap top level arrayref in a hash
if(UNIVERSAL::isa($ref, 'ARRAY')) {
$ref = { anon => $ref };
}
# Extract rootname from top level hash if keeproot enabled
if($self->{opt}->{keeproot}) {
my(@keys) = keys(%$ref);
if(@keys == 1) {
$ref = $ref->{$keys[0]};
$self->{opt}->{rootname} = $keys[0];
}
}
# Ensure there are no top level attributes if we're not adding root elements
elsif($self->{opt}->{rootname} eq '') {
if(UNIVERSAL::isa($ref, 'HASH')) {
my $refsave = $ref;
$ref = {};
foreach (keys(%$refsave)) {
if(ref($refsave->{$_})) {
$ref->{$_} = $refsave->{$_};
}
else {
$ref->{$_} = [ $refsave->{$_} ];
}
}
}
}
# Encode the hashref and write to file if necessary
$self->{_ancestors} = [];
my $xml = $self->value_to_xml($ref, $self->{opt}->{rootname}, '');
delete $self->{_ancestors};
if($self->{opt}->{xmldecl}) {
$xml = $self->{opt}->{xmldecl} . "\n" . $xml;
}
if($self->{opt}->{outputfile}) {
if(ref($self->{opt}->{outputfile})) {
my $fh = $self->{opt}->{outputfile};
if(UNIVERSAL::isa($fh, 'GLOB') and !UNIVERSAL::can($fh, 'print')) {
eval { require IO::Handle; };
croak $@ if $@;
}
return($fh->print($xml));
}
else {
local(*OUT);
open(OUT, '>', "$self->{opt}->{outputfile}") ||
croak "open($self->{opt}->{outputfile}): $!";
binmode(OUT, ':utf8') if($] >= 5.008);
print OUT $xml || croak "print: $!";
close(OUT);
}
}
elsif($self->{opt}->{handler}) {
require XML::SAX;
my $sp = XML::SAX::ParserFactory->parser(
Handler => $self->{opt}->{handler}
);
return($sp->parse_string($xml));
}
else {
return($xml);
}
}
##############################################################################
# Method: handle_options()
#
# Helper routine for both XMLin() and XMLout(). Both routines handle their
# first argument and assume all other args are options handled by this routine.
# Saves a hash of options in $self->{opt}.
#
# If default options were passed to the constructor, they will be retrieved
# here and merged with options supplied to the method call.
#
# First argument should be the string 'in' or the string 'out'.
#
# Remaining arguments should be name=>value pairs. Sets up default values
# for options not supplied. Unrecognised options are a fatal error.
#
sub handle_options {
my $self = shift;
my $dirn = shift;
# Determine valid options based on context
my %known_opt;
if($dirn eq 'in') {
@known_opt{@KnownOptIn} = @KnownOptIn;
}
else {
@known_opt{@KnownOptOut} = @KnownOptOut;
}
# Store supplied options in hashref and weed out invalid ones
if(@_ % 2) {
croak "Options must be name=>value pairs (odd number supplied)";
}
my %raw_opt = @_;
my $opt = {};
$self->{opt} = $opt;
while(my($key, $val) = each %raw_opt) {
my $lkey = lc($key);
$lkey =~ s/_//g;
croak "Unrecognised option: $key" unless($known_opt{$lkey});
$opt->{$lkey} = $val;
}
# Merge in options passed to constructor
foreach (keys(%known_opt)) {
unless(exists($opt->{$_})) {
if(exists($self->{def_opt}->{$_})) {
$opt->{$_} = $self->{def_opt}->{$_};
}
}
}
# Set sensible defaults if not supplied
if(exists($opt->{rootname})) {
unless(defined($opt->{rootname})) {
$opt->{rootname} = '';
}
}
else {
$opt->{rootname} = $DefRootName;
}
if($opt->{xmldecl} and $opt->{xmldecl} eq '1') {
$opt->{xmldecl} = $DefXmlDecl;
}
if(exists($opt->{contentkey})) {
if($opt->{contentkey} =~ m{^-(.*)$}) {
$opt->{contentkey} = $1;
$opt->{collapseagain} = 1;
}
}
else {
$opt->{contentkey} = $DefContentKey;
}
unless(exists($opt->{normalisespace})) {
$opt->{normalisespace} = $opt->{normalizespace};
}
$opt->{normalisespace} = 0 unless(defined($opt->{normalisespace}));
# Cleanups for values assumed to be arrays later
if($opt->{searchpath}) {
unless(ref($opt->{searchpath})) {
$opt->{searchpath} = [ $opt->{searchpath} ];
}
}
else {
$opt->{searchpath} = [ ];
}
if($opt->{cache} and !ref($opt->{cache})) {
$opt->{cache} = [ $opt->{cache} ];
}
if($opt->{cache}) {
$_ = lc($_) foreach (@{$opt->{cache}});
foreach my $scheme (@{$opt->{cache}}) {
my $method = 'cache_read_' . $scheme;
croak "Unsupported caching scheme: $scheme"
unless($self->can($method));
}
}
if(exists($opt->{parseropts})) {
if($^W) {
carp "Warning: " .
"'ParserOpts' is deprecated, contact the author if you need it";
}
}
else {
$opt->{parseropts} = [ ];
}
# Special cleanup for {forcearray} which could be regex, arrayref or boolean
# or left to default to 0
if(exists($opt->{forcearray})) {
if(ref($opt->{forcearray}) eq 'Regexp') {
$opt->{forcearray} = [ $opt->{forcearray} ];
}
if(ref($opt->{forcearray}) eq 'ARRAY') {
my @force_list = @{$opt->{forcearray}};
if(@force_list) {
$opt->{forcearray} = {};
foreach my $tag (@force_list) {
if(ref($tag) eq 'Regexp') {
push @{$opt->{forcearray}->{_regex}}, $tag;
}
else {
$opt->{forcearray}->{$tag} = 1;
}
}
}
else {
$opt->{forcearray} = 0;
}
}
else {
$opt->{forcearray} = ( $opt->{forcearray} ? 1 : 0 );
}
}
else {
if($StrictMode and $dirn eq 'in') {
croak "No value specified for 'ForceArray' option in call to XML$dirn()";
}
$opt->{forcearray} = 0;
}
# Special cleanup for {keyattr} which could be arrayref or hashref or left
# to default to arrayref
if(exists($opt->{keyattr})) {
if(ref($opt->{keyattr})) {
if(ref($opt->{keyattr}) eq 'HASH') {
# Make a copy so we can mess with it
$opt->{keyattr} = { %{$opt->{keyattr}} };
# Convert keyattr => { elem => '+attr' }
# to keyattr => { elem => [ 'attr', '+' ] }
foreach my $el (keys(%{$opt->{keyattr}})) {
if($opt->{keyattr}->{$el} =~ /^(\+|-)?(.*)$/) {
$opt->{keyattr}->{$el} = [ $2, ($1 ? $1 : '') ];
if($StrictMode and $dirn eq 'in') {
next if($opt->{forcearray} == 1);
next if(ref($opt->{forcearray}) eq 'HASH'
and $opt->{forcearray}->{$el});
croak "<$el> set in KeyAttr but not in ForceArray";
}
}
else {
delete($opt->{keyattr}->{$el}); # Never reached (famous last words?)
}
}
}
else {
if(@{$opt->{keyattr}} == 0) {
delete($opt->{keyattr});
}
}
}
else {
$opt->{keyattr} = [ $opt->{keyattr} ];
}
}
else {
if($StrictMode) {
croak "No value specified for 'KeyAttr' option in call to XML$dirn()";
}
$opt->{keyattr} = [ @DefKeyAttr ];
}
# Special cleanup for {valueattr} which could be arrayref or hashref
if(exists($opt->{valueattr})) {
if(ref($opt->{valueattr}) eq 'ARRAY') {
$opt->{valueattrlist} = {};
$opt->{valueattrlist}->{$_} = 1 foreach(@{ delete $opt->{valueattr} });
}
}
# make sure there's nothing weird in {grouptags}
if($opt->{grouptags}) {
croak "Illegal value for 'GroupTags' option - expected a hashref"
unless UNIVERSAL::isa($opt->{grouptags}, 'HASH');
while(my($key, $val) = each %{$opt->{grouptags}}) {
next if $key ne $val;
croak "Bad value in GroupTags: '$key' => '$val'";
}
}
# Check the {variables} option is valid and initialise variables hash
if($opt->{variables} and !UNIVERSAL::isa($opt->{variables}, 'HASH')) {
croak "Illegal value for 'Variables' option - expected a hashref";
}
if($opt->{variables}) {
$self->{_var_values} = { %{$opt->{variables}} };
}
elsif($opt->{varattr}) {
$self->{_var_values} = {};
}
}
##############################################################################
# Method: find_xml_file()
#
# Helper routine for XMLin().
# Takes a filename, and a list of directories, attempts to locate the file in
# the directories listed.
# Returns a full pathname on success; croaks on failure.
#
sub find_xml_file {
my $self = shift;
my $file = shift;
my @search_path = @_;
require File::Basename;
require File::Spec;
my($filename, $filedir) = File::Basename::fileparse($file);
if($filename ne $file) { # Ignore searchpath if dir component
return($file) if(-e $file);
}
else {
my($path);
foreach $path (@search_path) {
my $fullpath = File::Spec->catfile($path, $file);
return($fullpath) if(-e $fullpath);
}
}
# If user did not supply a search path, default to current directory
if(!@search_path) {
return($file) if(-e $file);
croak "File does not exist: $file";
}
croak "Could not find $file in ", join(':', @search_path);
}
##############################################################################
# Method: collapse()
#
# Helper routine for XMLin(). This routine really comprises the 'smarts' (or
# value add) of this module.
#
# Takes the parse tree that XML::Parser produced from the supplied XML and
# recurses through it 'collapsing' unnecessary levels of indirection (nested
# arrays etc) to produce a data structure that is easier to work with.
#
# Elements in the original parser tree are represented as an element name
# followed by an arrayref. The first element of the array is a hashref
# containing the attributes. The rest of the array contains a list of any
# nested elements as name+arrayref pairs:
#
# <element name>, [ { <attribute hashref> }, <element name>, [ ... ], ... ]
#
# The special element name '0' (zero) flags text content.
#
# This routine cuts down the noise by discarding any text content consisting of
# only whitespace and then moves the nested elements into the attribute hash
# using the name of the nested element as the hash key and the collapsed
# version of the nested element as the value. Multiple nested elements with
# the same name will initially be represented as an arrayref, but this may be
# 'folded' into a hashref depending on the value of the keyattr option.
#
sub collapse {
my $self = shift;
# Start with the hash of attributes
my $attr = shift;
if($self->{opt}->{noattr}) { # Discard if 'noattr' set
$attr = {};
}
elsif($self->{opt}->{normalisespace} == 2) {
while(my($key, $value) = each %$attr) {
$attr->{$key} = $self->normalise_space($value)
}
}
# Do variable substitutions
if(my $var = $self->{_var_values}) {
while(my($key, $val) = each(%$attr)) {
$val =~ s{\$\{([\w.]+)\}}{ $self->get_var($1) }ge;
$attr->{$key} = $val;
}
}