API/XML/Simple.pm untested

filter: Statementstmt 0.0% 0 / 784 Branchbran 0.0% 0 / 446 Conditioncond 0.0% 0 / 148 MC/DCmcdc 0.0% 0 / 91 Subroutinesub 0.0% 0 / 63 Podpod 0.0% 0 / 43 totaltotal 0.0% 0 / 1575 CC 224 SCAR 67.4
CC
224
Cov
0%
handle_options
2070.0
value_to_xml
2070.0
collapse
1260.0
CRAP 845.7
1 package Amazon::API::XML::Simple;
2 ## no critic
3 ########################################################################
4 # This module is derived from XML::Simple 2.25.
5 #
6 # XML::Simple has been effectively unmaintained since 2018 and its
7 # author recommends against using it for new code. Amazon::API still
8 # depends on its XML-to-Perl data structure semantics, which are a good
9 # fit for Botocore protocol response handling.
10 #
11 # This local copy is intentionally kept close to XML::Simple 2.25.
12 # Changes should be limited to behavior required by Amazon::API and
13 # covered by protocol tests.
14 #
15 # The original XML::Simple copyright and license terms are retained
16 # below.
17 ########################################################################
18  
19 use strict;
20 use warnings;
21  
22 our $VERSION = '2.25';
23  
24 =pod
25  
26 =head1 NAME
27  
28 XML::Simple - An API for simple XML files
29  
30 =head1 SYNOPSIS
31  
32 PLEASE DO NOT USE THIS MODULE IN NEW CODE. If you ignore this
33 warning and use it anyway, the C<qw(:strict)> mode will save you a little pain.
34  
35 use XML::Simple qw(:strict);
36  
37 my $ref = XMLin([<xml file or string>] [, <options>]);
38  
39 my $xml = XMLout($hashref [, <options>]);
40  
41 Or the object oriented way:
42  
43 require XML::Simple qw(:strict);
44  
45 my $xs = XML::Simple->new([<options>]);
46  
47 my $ref = $xs->XMLin([<xml file or string>] [, <options>]);
48  
49 my $xml = $xs->XMLout($hashref [, <options>]);
50  
51 (or see L<"SAX SUPPORT"> for 'the SAX way').
52  
53 Note, in these examples, the square brackets are used to denote optional items
54 not to imply items should be supplied in arrayrefs.
55  
56 =cut
57  
58 # See after __END__ for more POD documentation
59  
60 # Load essentials here, other modules loaded on demand later
61  
62 use strict;
63 use warnings;
64 use warnings::register;
65 use Carp;
66 use Scalar::Util qw();
67 require Exporter;
68  
69 ##############################################################################
70 # Define some constants
71 #
72  
73 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK $PREFERRED_PARSER);
74  
75 @ISA = qw(Exporter);
76 @EXPORT = qw(XMLin XMLout);
77 @EXPORT_OK = qw(xml_in xml_out);
78  
79 my %StrictMode = ();
80  
81 my @KnownOptIn = qw(keyattr keeproot forcecontent contentkey noattr
82 searchpath forcearray cache suppressempty parseropts
83 grouptags nsexpand datahandler varattr variables
84 normalisespace normalizespace valueattr strictmode);
85  
86 my @KnownOptOut = qw(keyattr keeproot contentkey noattr
87 rootname xmldecl outputfile noescape suppressempty
88 grouptags nsexpand handler noindent attrindent nosort
89 valueattr numericescape strictmode);
90  
91 my @DefKeyAttr = qw(name key id);
92 my $DefRootName = qq(opt);
93 my $DefContentKey = qq(content);
94 my $DefXmlDecl = qq(<?xml version='1.0' standalone='yes'?>);
95  
96 my $xmlns_ns = 'http://www.w3.org/2000/xmlns/';
97 my $bad_def_ns_jcn = '{' . $xmlns_ns . '}'; # LibXML::SAX workaround
98  
99 ##############################################################################
100 # Globals for use by caching routines
101 #
102  
103 my %MemShareCache = ();
104 my %MemCopyCache = ();
105  
106 ##############################################################################
107 # Wrapper for Exporter - handles ':strict'
108 #
109  
110 sub import {
111 # Handle the :strict tag
112  
113 my ($calling_package) = caller();
114 _strict_mode_for_caller(1) if grep( /^:strict$/, @_ );
115  
116 # Pass everything else to Exporter.pm
117  
118 @_ = grep( !/^:strict$/, @_ );
119 goto &Exporter::import;
120 }
121  
122 ##############################################################################
123 # Constructor for optional object interface.
124 #
125  
126 sub new {
127 my $class = shift;
128  
129 if ( @_ % 2 ) {
130 croak "Default options must be name=>value pairs (odd number supplied)";
131 }
132  
133 my %known_opt;
134 @known_opt{ @KnownOptIn, @KnownOptOut } = ();
135  
136 my %raw_opt = @_;
137 $raw_opt{strictmode} = _strict_mode_for_caller()
138 unless exists $raw_opt{strictmode};
139 my %def_opt;
140 while ( my ( $key, $val ) = each %raw_opt ) {
141 my $lkey = lc($key);
142 $lkey =~ s/_//g;
143 croak "Unrecognised option: $key" unless ( exists( $known_opt{$lkey} ) );
144 $def_opt{$lkey} = $val;
145 }
146 my $self = { def_opt => \%def_opt };
147  
148 return ( bless( $self, $class ) );
149 }
150  
151 ##############################################################################
152 # Sub: _strict_mode_for_caller()
153 #
154 # Gets or sets the XML::Simple :strict mode flag for the calling namespace.
155 # Walks back through call stack to find the calling namespace and sets the
156 # :strict mode flag for that namespace if an argument was supplied and returns
157 # the flag value if not.
158 #
159  
160 sub _strict_mode_for_caller {
161 my $set_mode = @_;
162 my $frame = 1;
163 while ( my ($package) = caller( $frame++ ) ) {
164 next if $package eq __PACKAGE__;
165 $StrictMode{$package} = 1 if $set_mode;
166 return $StrictMode{$package};
167 }
168 return (0);
169 }
170  
171 ##############################################################################
172 # Sub: _get_object()
173 #
174 # Helper routine called from XMLin() and XMLout() to create an object if none
175 # was provided. Note, this routine does mess with the caller's @_ array.
176 #
177  
178 sub _get_object {
179 my $self;
180 if ( $_[0] && UNIVERSAL::isa( $_[0], __PACKAGE__ ) ) {
181 $self = shift;
182 }
183 else {
184 $self = __PACKAGE__->new();
185 }
186  
187 return $self;
188 }
189  
190 ##############################################################################
191 # Sub/Method: XMLin()
192 #
193 # Exported routine for slurping XML into a hashref - see pod for info.
194 #
195 # May be called as object method or as a plain function.
196 #
197 # Expects one arg for the source XML, optionally followed by a number of
198 # name => value option pairs.
199 #
200  
201 sub XMLin {
202 my $self = &_get_object; # note, @_ is passed implicitly
203  
204 my $target = shift;
205  
206 # Work out whether to parse a string, a file or a filehandle
207  
208 if ( not defined $target ) {
209 return $self->parse_file( undef, @_ );
210 }
211  
212 elsif ( $target eq '-' ) {
213 local ($/) = undef;
214 $target = <STDIN>;
215 return $self->parse_string( \$target, @_ );
216 }
217  
218 elsif ( my $type = ref($target) ) {
219 if ( $type eq 'SCALAR' ) {
220 return $self->parse_string( $target, @_ );
221 }
222 else {
223 return $self->parse_fh( $target, @_ );
224 }
225 }
226  
227 elsif ( $target =~ m{<.*?>}s ) {
228 return $self->parse_string( \$target, @_ );
229 }
230  
231 else {
232 return $self->parse_file( $target, @_ );
233 }
234 }
235  
236 ##############################################################################
237 # Sub/Method: parse_file()
238 #
239 # Same as XMLin, but only parses from a named file.
240 #
241  
242 sub parse_file {
243 my $self = &_get_object; # note, @_ is passed implicitly
244  
245 my $filename = shift;
246  
247 $self->handle_options( 'in', @_ );
248  
249 $filename = $self->default_config_file if not defined $filename;
250  
251 $filename = $self->find_xml_file( $filename, @{ $self->{opt}->{searchpath} } );
252  
253 # Check cache for previous parse
254  
255 if ( $self->{opt}->{cache} ) {
256 foreach my $scheme ( @{ $self->{opt}->{cache} } ) {
257 my $method = 'cache_read_' . $scheme;
258 my $opt = $self->$method($filename);
259 return ($opt) if ($opt);
260 }
261 }
262  
263 my $ref = $self->build_simple_tree( $filename, undef );
264  
265 if ( $self->{opt}->{cache} ) {
266 my $method = 'cache_write_' . $self->{opt}->{cache}->[0];
267 $self->$method( $ref, $filename );
268 }
269  
270 return $ref;
271 }
272  
273 ##############################################################################
274 # Sub/Method: parse_fh()
275 #
276 # Same as XMLin, but only parses from a filehandle.
277 #
278  
279 sub parse_fh {
280 my $self = &_get_object; # note, @_ is passed implicitly
281  
282 my $fh = shift;
283 croak "Can't use " . ( defined $fh ? qq{string ("$fh")} : 'undef' ) . " as a filehandle" unless ref $fh;
284  
285 $self->handle_options( 'in', @_ );
286  
287 return $self->build_simple_tree( undef, $fh );
288 }
289  
290 ##############################################################################
291 # Sub/Method: parse_string()
292 #
293 # Same as XMLin, but only parses from a string or a reference to a string.
294 #
295  
296 sub parse_string {
297 my $self = &_get_object; # note, @_ is passed implicitly
298  
299 my $string = shift;
300  
301 $self->handle_options( 'in', @_ );
302  
303 return $self->build_simple_tree( undef, ref $string ? $string : \$string );
304 }
305  
306 ##############################################################################
307 # Method: default_config_file()
308 #
309 # Returns the name of the XML file to parse if no filename (or XML string)
310 # was provided.
311 #
312  
313 sub default_config_file {
314 my $self = shift;
315  
316 require File::Basename;
317  
318 my ( $basename, $script_dir, $ext ) = File::Basename::fileparse( $0, '\.[^\.]+' );
319  
320 # Add script directory to searchpath
321  
322 if ($script_dir) {
323 unshift( @{ $self->{opt}->{searchpath} }, $script_dir );
324 }
325  
326 return $basename . '.xml';
327 }
328  
329 ##############################################################################
330 # Method: build_simple_tree()
331 #
332 # Builds a 'tree' data structure as provided by XML::Parser and then
333 # 'simplifies' it as specified by the various options in effect.
334 #
335  
336 sub build_simple_tree {
337 my $self = shift;
338  
339 my $tree = eval { $self->build_tree(@_); };
340 Carp::croak("$@XML::Simple called") if $@;
341  
342 return $self->{opt}->{keeproot}
343 ? $self->collapse( {}, @$tree )
344 : $self->collapse( @{ $tree->[1] } );
345 }
346  
347 ##############################################################################
348 # Method: build_tree()
349 #
350 # This routine will be called if there is no suitable pre-parsed tree in a
351 # cache. It parses the XML and returns an XML::Parser 'Tree' style data
352 # structure (summarised in the comments for the collapse() routine below).
353 #
354 # XML::Simple requires the services of another module that knows how to parse
355 # XML. If XML::SAX is installed, the default SAX parser will be used,
356 # otherwise XML::Parser will be used.
357 #
358 # This routine expects to be passed a filename as argument 1 or a 'string' as
359 # argument 2. The 'string' might be a string of XML (passed by reference to
360 # save memory) or it might be a reference to an IO::Handle. (This
361 # non-intuitive mess results in part from the way XML::Parser works but that's
362 # really no excuse).
363 #
364  
365 sub build_tree {
366 my $self = shift;
367 my $filename = shift;
368 my $string = shift;
369  
370 my $preferred_parser = $PREFERRED_PARSER;
371 unless ( defined($preferred_parser) ) {
372 $preferred_parser = $ENV{XML_SIMPLE_PREFERRED_PARSER} || '';
373 }
374 if ( $preferred_parser eq 'XML::Parser' ) {
375 return ( $self->build_tree_xml_parser( $filename, $string ) );
376 }
377  
378 eval { require XML::SAX; }; # We didn't need it until now
379 if ($@) { # No XML::SAX - fall back to XML::Parser
380 if ($preferred_parser) { # unless a SAX parser was expressly requested
381 croak "XMLin() could not load XML::SAX";
382 }
383 return ( $self->build_tree_xml_parser( $filename, $string ) );
384 }
385  
386 $XML::SAX::ParserPackage = $preferred_parser if ($preferred_parser);
387  
388 my $sp = XML::SAX::ParserFactory->parser( Handler => $self );
389  
390 $self->{nocollapse} = 1;
391 my ($tree);
392 if ($filename) {
393 $tree = $sp->parse_uri($filename);
394 }
395 else {
396 if ( ref($string) && ref($string) ne 'SCALAR' ) {
397 $tree = $sp->parse_file($string);
398 }
399 else {
400 $tree = $sp->parse_string($$string);
401 }
402 }
403  
404 return ($tree);
405 }
406  
407 ##############################################################################
408 # Method: build_tree_xml_parser()
409 #
410 # This routine will be called if XML::SAX is not installed, or if XML::Parser
411 # was specifically requested. It takes the same arguments as build_tree() and
412 # returns the same data structure (XML::Parser 'Tree' style).
413 #
414  
415 sub build_tree_xml_parser {
416 my $self = shift;
417 my $filename = shift;
418 my $string = shift;
419  
420 eval {
421 local ($^W) = 0; # Suppress warning from Expat.pm re File::Spec::load()
422 require XML::Parser; # We didn't need it until now
423 };
424 if ($@) {
425 croak "XMLin() requires either XML::SAX or XML::Parser";
426 }
427  
428 if ( $self->{opt}->{nsexpand} ) {
429 carp "'nsexpand' option requires XML::SAX";
430 }
431  
432 my $xp = $self->new_xml_parser();
433  
434 my ($tree);
435 if ($filename) {
436 # $tree = $xp->parsefile($filename); # Changed due to prob w/mod_perl
437 open( my $xfh, '<', $filename ) || croak qq($filename - $!);
438 $tree = $xp->parse($xfh);
439 }
440 else {
441 $tree = $xp->parse($$string);
442 }
443  
444 return ($tree);
445 }
446  
447 ##############################################################################
448 # Method: new_xml_parser()
449 #
450 # Simply calls the XML::Parser constructor. Override this method to customise
451 # the behaviour of the parser.
452 #
453  
454 sub new_xml_parser {
455 my ($self) = @_;
456  
457 my $xp = XML::Parser->new( Style => 'Tree', @{ $self->{opt}->{parseropts} } );
458 $xp->setHandlers( ExternEnt => sub { return $_[2] } );
459  
460 return $xp;
461 }
462  
463 ##############################################################################
464 # Method: cache_write_storable()
465 #
466 # Wrapper routine for invoking Storable::nstore() to cache a parsed data
467 # structure.
468 #
469  
470 sub cache_write_storable {
471 my ( $self, $data, $filename ) = @_;
472  
473 my $cachefile = $self->storable_filename($filename);
474  
475 require Storable; # We didn't need it until now
476  
477 if ( 'VMS' eq $^O ) {
478 Storable::nstore( $data, $cachefile );
479 }
480 else {
481 # If the following line fails for you, your Storable.pm is old - upgrade
482 Storable::lock_nstore( $data, $cachefile );
483 }
484  
485 }
486  
487 ##############################################################################
488 # Method: cache_read_storable()
489 #
490 # Wrapper routine for invoking Storable::retrieve() to read a cached parsed
491 # data structure. Only returns cached data if the cache file exists and is
492 # newer than the source XML file.
493 #
494  
495 sub cache_read_storable {
496 my ( $self, $filename ) = @_;
497  
498 my $cachefile = $self->storable_filename($filename);
499  
500 return unless ( -r $cachefile );
501 return unless ( ( stat($cachefile) )[9] > ( stat($filename) )[9] );
502  
503 require Storable; # We didn't need it until now
504  
505 if ( 'VMS' eq $^O ) {
506 return ( Storable::retrieve($cachefile) );
507 }
508 else {
509 return ( Storable::lock_retrieve($cachefile) );
510 }
511  
512 }
513  
514 ##############################################################################
515 # Method: storable_filename()
516 #
517 # Translates the supplied source XML filename into a filename for the storable
518 # cached data. A '.stor' suffix is added after stripping an optional '.xml'
519 # suffix.
520 #
521  
522 sub storable_filename {
523 my ( $self, $cachefile ) = @_;
524  
525 $cachefile =~ s{(\.xml)?$}{.stor};
526 return $cachefile;
527 }
528  
529 ##############################################################################
530 # Method: cache_write_memshare()
531 #
532 # Takes the supplied data structure reference and stores it away in a global
533 # hash structure.
534 #
535  
536 sub cache_write_memshare {
537 my ( $self, $data, $filename ) = @_;
538  
539 $MemShareCache{$filename} = [ time(), $data ];
540 }
541  
542 ##############################################################################
543 # Method: cache_read_memshare()
544 #
545 # Takes a filename and looks in a global hash for a cached parsed version.
546 #
547  
548 sub cache_read_memshare {
549 my ( $self, $filename ) = @_;
550  
551 return unless ( $MemShareCache{$filename} );
552 return unless ( $MemShareCache{$filename}->[0] > ( stat($filename) )[9] );
553  
554 return ( $MemShareCache{$filename}->[1] );
555  
556 }
557  
558 ##############################################################################
559 # Method: cache_write_memcopy()
560 #
561 # Takes the supplied data structure and stores a copy of it in a global hash
562 # structure.
563 #
564  
565 sub cache_write_memcopy {
566 my ( $self, $data, $filename ) = @_;
567  
568 require Storable; # We didn't need it until now
569  
570 $MemCopyCache{$filename} = [ time(), Storable::dclone($data) ];
571 }
572  
573 ##############################################################################
574 # Method: cache_read_memcopy()
575 #
576 # Takes a filename and looks in a global hash for a cached parsed version.
577 # Returns a reference to a copy of that data structure.
578 #
579  
580 sub cache_read_memcopy {
581 my ( $self, $filename ) = @_;
582  
583 return unless ( $MemCopyCache{$filename} );
584 return unless ( $MemCopyCache{$filename}->[0] > ( stat($filename) )[9] );
585  
586 return ( Storable::dclone( $MemCopyCache{$filename}->[1] ) );
587  
588 }
589  
590 ##############################################################################
591 # Sub/Method: XMLout()
592 #
593 # Exported routine for 'unslurping' a data structure out to XML.
594 #
595 # Expects a reference to a data structure and an optional list of option
596 # name => value pairs.
597 #
598  
599 sub XMLout {
600 my $self = &_get_object; # note, @_ is passed implicitly
601  
602 croak "XMLout() requires at least one argument" unless (@_);
603 my $ref = shift;
604  
605 $self->handle_options( 'out', @_ );
606  
607 # If namespace expansion is set, XML::NamespaceSupport is required
608  
609 if ( $self->{opt}->{nsexpand} ) {
610 require XML::NamespaceSupport;
611 $self->{nsup} = XML::NamespaceSupport->new();
612 $self->{ns_prefix} = 'aaa';
613 }
614  
615 # Wrap top level arrayref in a hash
616  
617 if ( UNIVERSAL::isa( $ref, 'ARRAY' ) ) {
618 $ref = { anon => $ref };
619 }
620  
621 # Extract rootname from top level hash if keeproot enabled
622  
623 if ( $self->{opt}->{keeproot} ) {
624 my (@keys) = keys(%$ref);
625 if ( @keys == 1 ) {
626 $ref = $ref->{ $keys[0] };
627 $self->{opt}->{rootname} = $keys[0];
628 }
629 }
630  
631 # Ensure there are no top level attributes if we're not adding root elements
632  
633 elsif ( $self->{opt}->{rootname} eq '' ) {
634 if ( UNIVERSAL::isa( $ref, 'HASH' ) ) {
635 my $refsave = $ref;
636 $ref = {};
637 foreach ( keys(%$refsave) ) {
638 if ( ref( $refsave->{$_} ) ) {
639 $ref->{$_} = $refsave->{$_};
640 }
641 else {
642 $ref->{$_} = [ $refsave->{$_} ];
643 }
644 }
645 }
646 }
647  
648 # Encode the hashref and write to file if necessary
649  
650 $self->{_ancestors} = {};
651 my $xml = $self->value_to_xml( $ref, $self->{opt}->{rootname}, '' );
652 delete $self->{_ancestors};
653  
654 if ( $self->{opt}->{xmldecl} ) {
655 $xml = $self->{opt}->{xmldecl} . "\n" . $xml;
656 }
657  
658 if ( $self->{opt}->{outputfile} ) {
659 if ( ref( $self->{opt}->{outputfile} ) ) {
660 my $fh = $self->{opt}->{outputfile};
661 if ( UNIVERSAL::isa( $fh, 'GLOB' ) and !UNIVERSAL::can( $fh, 'print' ) ) {
662 eval { require IO::Handle; };
663 croak $@ if $@;
664 }
665 return ( $fh->print($xml) );
666 }
667 else {
668 open( my $out, '>', "$self->{opt}->{outputfile}" )
669 || croak "open($self->{opt}->{outputfile}): $!";
670 binmode( $out, ':utf8' ) if ( $] >= 5.008 );
671 print $out $xml or croak "print: $!";
672 close $out or croak "close: $!";
673 }
674 }
675 elsif ( $self->{opt}->{handler} ) {
676 require XML::SAX;
677 my $sp = XML::SAX::ParserFactory->parser( Handler => $self->{opt}->{handler} );
678 return ( $sp->parse_string($xml) );
679 }
680 else {
681 return ($xml);
682 }
683 }
684  
685 ##############################################################################
686 # Method: handle_options()
687 #
688 # Helper routine for both XMLin() and XMLout(). Both routines handle their
689 # first argument and assume all other args are options handled by this routine.
690 # Saves a hash of options in $self->{opt}.
691 #
692 # If default options were passed to the constructor, they will be retrieved
693 # here and merged with options supplied to the method call.
694 #
695 # First argument should be the string 'in' or the string 'out'.
696 #
697 # Remaining arguments should be name=>value pairs. Sets up default values
698 # for options not supplied. Unrecognised options are a fatal error.
699 #
700  
701 sub handle_options {
702 my $self = shift;
703 my $dirn = shift;
704  
705 # Determine valid options based on context
706  
707 my %known_opt;
708 if ( $dirn eq 'in' ) {
709 @known_opt{@KnownOptIn} = @KnownOptIn;
710 }
711 else {
712 @known_opt{@KnownOptOut} = @KnownOptOut;
713 }
714  
715 # Store supplied options in hashref and weed out invalid ones
716  
717 if ( @_ % 2 ) {
718 croak "Options must be name=>value pairs (odd number supplied)";
719 }
720 my %raw_opt = @_;
721 my $opt = {};
722 $self->{opt} = $opt;
723  
724 while ( my ( $key, $val ) = each %raw_opt ) {
725 my $lkey = lc($key);
726 $lkey =~ s/_//g;
727 croak "Unrecognised option: $key" unless ( $known_opt{$lkey} );
728 $opt->{$lkey} = $val;
729 }
730  
731 # Merge in options passed to constructor
732  
733 foreach ( keys(%known_opt) ) {
734 unless ( exists( $opt->{$_} ) ) {
735 if ( exists( $self->{def_opt}->{$_} ) ) {
736 $opt->{$_} = $self->{def_opt}->{$_};
737 }
738 }
739 }
740  
741 # Set sensible defaults if not supplied
742  
743 if ( exists( $opt->{rootname} ) ) {
744 unless ( defined( $opt->{rootname} ) ) {
745 $opt->{rootname} = '';
746 }
747 }
748 else {
749 $opt->{rootname} = $DefRootName;
750 }
751  
752 if ( $opt->{xmldecl} and $opt->{xmldecl} eq '1' ) {
753 $opt->{xmldecl} = $DefXmlDecl;
754 }
755  
756 if ( exists( $opt->{contentkey} ) ) {
757 if ( $opt->{contentkey} =~ m{^-(.*)$} ) {
758 $opt->{contentkey} = $1;
759 $opt->{collapseagain} = 1;
760 }
761 }
762 else {
763 $opt->{contentkey} = $DefContentKey;
764 }
765  
766 unless ( exists( $opt->{normalisespace} ) ) {
767 $opt->{normalisespace} = $opt->{normalizespace};
768 }
769 $opt->{normalisespace} = 0 unless ( defined( $opt->{normalisespace} ) );
770  
771 # Cleanups for values assumed to be arrays later
772  
773 if ( $opt->{searchpath} ) {
774 unless ( ref( $opt->{searchpath} ) ) {
775 $opt->{searchpath} = [ $opt->{searchpath} ];
776 }
777 }
778 else {
779 $opt->{searchpath} = [];
780 }
781  
782 if ( $opt->{cache} and !ref( $opt->{cache} ) ) {
783 $opt->{cache} = [ $opt->{cache} ];
784 }
785 if ( $opt->{cache} ) {
786 $_ = lc($_) foreach ( @{ $opt->{cache} } );
787 foreach my $scheme ( @{ $opt->{cache} } ) {
788 my $method = 'cache_read_' . $scheme;
789 croak "Unsupported caching scheme: $scheme"
790 unless ( $self->can($method) );
791 }
792 }
793  
794 if ( exists( $opt->{parseropts} ) ) {
795 if ( warnings::enabled() ) {
796 carp "Warning: " . "'ParserOpts' is deprecated, contact the author if you need it";
797 }
798 }
799 else {
800 $opt->{parseropts} = [];
801 }
802  
803 # Special cleanup for {forcearray} which could be regex, arrayref or boolean
804 # or left to default to 0
805  
806 if ( exists( $opt->{forcearray} ) ) {
807 if ( ref( $opt->{forcearray} ) eq 'Regexp' ) {
808 $opt->{forcearray} = [ $opt->{forcearray} ];
809 }
810  
811 if ( ref( $opt->{forcearray} ) eq 'ARRAY' ) {
812 my @force_list = @{ $opt->{forcearray} };
813 if (@force_list) {
814 $opt->{forcearray} = {};
815 foreach my $tag (@force_list) {
816 if ( ref($tag) eq 'Regexp' ) {
817 push @{ $opt->{forcearray}->{_regex} }, $tag;
818 }
819 else {
820 $opt->{forcearray}->{$tag} = 1;
821 }
822 }
823 }
824 else {
825 $opt->{forcearray} = 0;
826 }
827 }
828 else {
829 $opt->{forcearray} = ( $opt->{forcearray} ? 1 : 0 );
830 }
831 }
832 else {
833 if ( $opt->{strictmode} and $dirn eq 'in' ) {
834 croak "No value specified for 'ForceArray' option in call to XML$dirn()";
835 }
836 $opt->{forcearray} = 0;
837 }
838  
839 # Special cleanup for {keyattr} which could be arrayref or hashref or left
840 # to default to arrayref
841  
842 if ( exists( $opt->{keyattr} ) ) {
843 if ( ref( $opt->{keyattr} ) ) {
844 if ( ref( $opt->{keyattr} ) eq 'HASH' ) {
845  
846 # Make a copy so we can mess with it
847  
848 $opt->{keyattr} = { %{ $opt->{keyattr} } };
849  
850 # Convert keyattr => { elem => '+attr' }
851 # to keyattr => { elem => [ 'attr', '+' ] }
852  
853 foreach my $el ( keys( %{ $opt->{keyattr} } ) ) {
854 if ( $opt->{keyattr}->{$el} =~ /^(\+|-)?(.*)$/ ) {
855 $opt->{keyattr}->{$el} = [ $2, ( $1 ? $1 : '' ) ];
856 if ( $opt->{strictmode} and $dirn eq 'in' ) {
857 next if ( $opt->{forcearray} == 1 );
858 next if ( ref( $opt->{forcearray} ) eq 'HASH'
859 and $opt->{forcearray}->{$el} );
860 croak "<$el> set in KeyAttr but not in ForceArray";
861 }
862 }
863 else {
864 delete( $opt->{keyattr}->{$el} ); # Never reached (famous last words?)
865 }
866 }
867 }
868 else {
869 if ( @{ $opt->{keyattr} } == 0 ) {
870 delete( $opt->{keyattr} );
871 }
872 }
873 }
874 else {
875 $opt->{keyattr} = [ $opt->{keyattr} ];
876 }
877 }
878 else {
879 if ( $opt->{strictmode} ) {
880 croak "No value specified for 'KeyAttr' option in call to XML$dirn()";
881 }
882 $opt->{keyattr} = [@DefKeyAttr];
883 }
884  
885 # Special cleanup for {valueattr} which could be arrayref or hashref
886  
887 if ( exists( $opt->{valueattr} ) ) {
888 if ( ref( $opt->{valueattr} ) eq 'ARRAY' ) {
889 $opt->{valueattrlist} = {};
890 $opt->{valueattrlist}->{$_} = 1 foreach ( @{ delete $opt->{valueattr} } );
891 }
892 }
893  
894 # make sure there's nothing weird in {grouptags}
895  
896 if ( $opt->{grouptags} ) {
897 croak "Illegal value for 'GroupTags' option - expected a hashref"
898 unless UNIVERSAL::isa( $opt->{grouptags}, 'HASH' );
899  
900 while ( my ( $key, $val ) = each %{ $opt->{grouptags} } ) {
901 next if $key ne $val;
902 croak "Bad value in GroupTags: '$key' => '$val'";
903 }
904 }
905  
906 # Check the {variables} option is valid and initialise variables hash
907  
908 if ( $opt->{variables} and !UNIVERSAL::isa( $opt->{variables}, 'HASH' ) ) {
909 croak "Illegal value for 'Variables' option - expected a hashref";
910 }
911  
912 if ( $opt->{variables} ) {
913 $self->{_var_values} = { %{ $opt->{variables} } };
914 }
915 elsif ( $opt->{varattr} ) {
916 $self->{_var_values} = {};
917 }
918  
919 }
920  
921 ##############################################################################
922 # Method: find_xml_file()
923 #
924 # Helper routine for XMLin().
925 # Takes a filename, and a list of directories, attempts to locate the file in
926 # the directories listed.
927 # Returns a full pathname on success; croaks on failure.
928 #
929  
930 sub find_xml_file {
931 my $self = shift;
932 my $file = shift;
933 my @search_path = @_;
934  
935 require File::Basename;
936 require File::Spec;
937  
938 my ( $filename, $filedir ) = File::Basename::fileparse($file);
939  
940 if ( $filename ne $file ) { # Ignore searchpath if dir component
941 return ($file) if ( -e $file );
942 }
943 else {
944 my ($path);
945 foreach $path (@search_path) {
946 my $fullpath = File::Spec->catfile( $path, $file );
947 return ($fullpath) if ( -e $fullpath );
948 }
949 }
950  
951 # If user did not supply a search path, default to current directory
952  
953 if ( !@search_path ) {
954 return ($file) if ( -e $file );
955 croak "File does not exist: $file";
956 }
957  
958 croak "Could not find $file in ", join( ':', @search_path );
959 }
960  
961 ##############################################################################
962 # Method: collapse()
963 #
964 # Helper routine for XMLin(). This routine really comprises the 'smarts' (or
965 # value add) of this module.
966 #
967 # Takes the parse tree that XML::Parser produced from the supplied XML and
968 # recurses through it 'collapsing' unnecessary levels of indirection (nested
969 # arrays etc) to produce a data structure that is easier to work with.
970 #
971 # Elements in the original parser tree are represented as an element name
972 # followed by an arrayref. The first element of the array is a hashref
973 # containing the attributes. The rest of the array contains a list of any
974 # nested elements as name+arrayref pairs:
975 #
976 # <element name>, [ { <attribute hashref> }, <element name>, [ ... ], ... ]
977 #
978 # The special element name '0' (zero) flags text content.
979 #
980 # This routine cuts down the noise by discarding any text content consisting of
981 # only whitespace and then moves the nested elements into the attribute hash
982 # using the name of the nested element as the hash key and the collapsed
983 # version of the nested element as the value. Multiple nested elements with
984 # the same name will initially be represented as an arrayref, but this may be
985 # 'folded' into a hashref depending on the value of the keyattr option.
986 #
987  
988 sub collapse {
989 my $self = shift;
990  
991 # Start with the hash of attributes
992  
993 my $attr = shift;
994 if ( $self->{opt}->{noattr} ) { # Discard if 'noattr' set
995 $attr = $self->new_hashref;
996 }
997 elsif ( $self->{opt}->{normalisespace} == 2 ) {
998 while ( my ( $key, $value ) = each %$attr ) {
999 $attr->{$key} = $self->normalise_space($value);
1000 }
1001 }
1002  
1003 # Do variable substitutions
1004  
1005 if ( my $var = $self->{_var_values} ) {
1006 while ( my ( $key, $val ) = each(%$attr) ) {
1007 $val =~ s^\$\{([\w.]+)\}^ $self->get_var($1) ^ge;
1008 $attr->{$key} = $val;
1009 }
1010 }
1011  
1012 # Roll up 'value' attributes (but only if no nested elements)
1013  
1014 if ( !@_ and keys %$attr == 1 ) {
1015 my ($k) = keys %$attr;
1016 if ( $self->{opt}->{valueattrlist} and $self->{opt}->{valueattrlist}->{$k} ) {
1017 return $attr->{$k};
1018 }
1019 }
1020  
1021 # Add any nested elements
1022  
1023 my ( $key, $val );
1024 while (@_) {
1025 $key = shift;
1026 $val = shift;
1027 $val = '' if not defined $val;
1028  
1029 if ( ref($val) ) {
1030 $val = $self->collapse(@$val);
1031 next if ( !defined($val) and $self->{opt}->{suppressempty} );
1032 }
1033 elsif ( $key eq '0' ) {
1034 # XML::Simple 2.25 unconditionally discards whitespace-only character
1035 # data here. That conflicts with NormaliseSpace => 0, where Amazon::API
1036 # must preserve the wire value exactly for REST-XML responses.
1037 #
1038 # For example:
1039 #
1040 # <stringValue> </stringValue>
1041 #
1042 # must deserialize as q{ }, not as an empty value.
1043 #
1044 # Preserve whitespace-only content when normalization is disabled.
1045 next
1046 if $self->{opt}->{normalisespace}
1047 && $val =~ m{^\s*$}s;
1048 next if $self->{opt}{normalisepace} && $val =~ m{^\s*$}s; # Skip all whitespace content
1049  
1050 $val = $self->normalise_space($val)
1051 if ( $self->{opt}->{normalisespace} == 2 );
1052  
1053 # do variable substitutions
1054  
1055 if ( my $var = $self->{_var_values} ) {
1056 $val =~ s^\$\{(\w+)\}^ $self->get_var($1) ^ge;
1057 }
1058  
1059 # look for variable definitions
1060  
1061 if ( my $var = $self->{opt}->{varattr} ) {
1062 if ( exists $attr->{$var} ) {
1063 $self->set_var( $attr->{$var}, $val );
1064 }
1065 }
1066  
1067 # Collapse text content in element with no attributes to a string
1068  
1069 if ( !%$attr and !@_ ) {
1070 return ( $self->{opt}->{forcecontent} ? { $self->{opt}->{contentkey} => $val } : $val );
1071 }
1072 $key = $self->{opt}->{contentkey};
1073 }
1074  
1075 # Combine duplicate attributes into arrayref if required
1076  
1077 if ( exists( $attr->{$key} ) ) {
1078 if ( UNIVERSAL::isa( $attr->{$key}, 'ARRAY' ) ) {
1079 push( @{ $attr->{$key} }, $val );
1080 }
1081 else {
1082 $attr->{$key} = [ $attr->{$key}, $val ];
1083 }
1084 }
1085 elsif ( defined($val) and UNIVERSAL::isa( $val, 'ARRAY' ) ) {
1086 $attr->{$key} = [$val];
1087 }
1088 else {
1089 if (
1090 $key ne $self->{opt}->{contentkey}
1091 and (
1092 ( $self->{opt}->{forcearray} == 1 )
1093 or (
1094 ( ref( $self->{opt}->{forcearray} ) eq 'HASH' )
1095 and ( $self->{opt}->{forcearray}->{$key}
1096 or ( grep $key =~ $_, @{ $self->{opt}->{forcearray}->{_regex} } ) )
1097 )
1098 )
1099 ) {
1100 $attr->{$key} = [$val];
1101 }
1102 else {
1103 $attr->{$key} = $val;
1104 }
1105 }
1106  
1107 }
1108  
1109 # Turn arrayrefs into hashrefs if key fields present
1110  
1111 if ( $self->{opt}->{keyattr} ) {
1112 while ( ( $key, $val ) = each %$attr ) {
1113 if ( defined($val) and UNIVERSAL::isa( $val, 'ARRAY' ) ) {
1114 $attr->{$key} = $self->array_to_hash( $key, $val );
1115 }
1116 }
1117 }
1118  
1119 # disintermediate grouped tags
1120  
1121 if ( $self->{opt}->{grouptags} ) {
1122 while ( my ( $key, $val ) = each(%$attr) ) {
1123 next unless ( UNIVERSAL::isa( $val, 'HASH' ) and ( keys %$val == 1 ) );
1124 next unless ( exists( $self->{opt}->{grouptags}->{$key} ) );
1125  
1126 my ( $child_key, $child_val ) = %$val;
1127  
1128 if ( $self->{opt}->{grouptags}->{$key} eq $child_key ) {
1129 $attr->{$key} = $child_val;
1130 }
1131 }
1132 }
1133  
1134 # Fold hashes containing a single anonymous array up into just the array
1135  
1136 my $count = scalar keys %$attr;
1137 if ( $count == 1
1138 and exists $attr->{anon}
1139 and UNIVERSAL::isa( $attr->{anon}, 'ARRAY' ) ) {
1140 return ( $attr->{anon} );
1141 }
1142  
1143 # Do the right thing if hash is empty, otherwise just return it
1144  
1145 if ( !%$attr and exists( $self->{opt}->{suppressempty} ) ) {
1146 if ( defined( $self->{opt}->{suppressempty} )
1147 and $self->{opt}->{suppressempty} eq '' ) {
1148 return ('');
1149 }
1150 return (undef);
1151 }
1152  
1153 # Roll up named elements with named nested 'value' attributes
1154  
1155 if ( $self->{opt}->{valueattr} ) {
1156 while ( my ( $key, $val ) = each(%$attr) ) {
1157 next unless ( $self->{opt}->{valueattr}->{$key} );
1158 next unless ( UNIVERSAL::isa( $val, 'HASH' ) and ( keys %$val == 1 ) );
1159 my ($k) = keys %$val;
1160 next unless ( $k eq $self->{opt}->{valueattr}->{$key} );
1161 $attr->{$key} = $val->{$k};
1162 }
1163 }
1164  
1165 return ($attr);
1166  
1167 }
1168  
1169 ##############################################################################
1170 # Method: set_var()
1171 #
1172 # Called when a variable definition is encountered in the XML. (A variable
1173 # definition looks like <element attrname="name">value</element> where attrname
1174 # matches the varattr setting).
1175 #
1176  
1177 sub set_var {
1178 my ( $self, $name, $value ) = @_;
1179  
1180 $self->{_var_values}->{$name} = $value;
1181 }
1182  
1183 ##############################################################################
1184 # Method: get_var()
1185 #
1186 # Called during variable substitution to get the value for the named variable.
1187 #
1188  
1189 sub get_var {
1190 my ( $self, $name ) = @_;
1191  
1192 my $value = $self->{_var_values}->{$name};
1193 return $value if ( defined($value) );
1194  
1195 return '${' . $name . '}';
1196 }
1197  
1198 ##############################################################################
1199 # Method: normalise_space()
1200 #
1201 # Strips leading and trailing whitespace and collapses sequences of whitespace
1202 # characters to a single space.
1203 #
1204  
1205 sub normalise_space {
1206 my ( $self, $text ) = @_;
1207  
1208 $text =~ s/^\s+//s;
1209 $text =~ s/\s+$//s;
1210 $text =~ s/\s\s+/ /sg;
1211  
1212 return $text;
1213 }
1214  
1215 ##############################################################################
1216 # Method: array_to_hash()
1217 #
1218 # Helper routine for collapse().
1219 # Attempts to 'fold' an array of hashes into an hash of hashes. Returns a
1220 # reference to the hash on success or the original array if folding is
1221 # not possible. Behaviour is controlled by 'keyattr' option.
1222 #
1223  
1224 sub array_to_hash {
1225 my $self = shift;
1226 my $name = shift;
1227 my $arrayref = shift;
1228  
1229 my $hashref = $self->new_hashref;
1230  
1231 my ( $i, $key, $val, $flag );
1232  
1233 # Handle keyattr => { .... }
1234  
1235 if ( ref( $self->{opt}->{keyattr} ) eq 'HASH' ) {
1236 return ($arrayref) unless ( exists( $self->{opt}->{keyattr}->{$name} ) );
1237 ( $key, $flag ) = @{ $self->{opt}->{keyattr}->{$name} };
1238 for ( $i = 0; $i < @$arrayref; $i++ ) {
1239 if ( UNIVERSAL::isa( $arrayref->[$i], 'HASH' )
1240 and exists( $arrayref->[$i]->{$key} ) ) {
1241 $val = $arrayref->[$i]->{$key};
1242 if ( ref($val) ) {
1243 $self->die_or_warn("<$name> element has non-scalar '$key' key attribute");
1244 return ($arrayref);
1245 }
1246 $val = $self->normalise_space($val)
1247 if ( $self->{opt}->{normalisespace} == 1 );
1248 $self->die_or_warn("<$name> element has non-unique value in '$key' key attribute: $val")
1249 if ( exists( $hashref->{$val} ) );
1250 $hashref->{$val} = $self->new_hashref( %{ $arrayref->[$i] } );
1251 $hashref->{$val}->{"-$key"} = $hashref->{$val}->{$key} if ( $flag eq '-' );
1252 delete $hashref->{$val}->{$key} unless ( $flag eq '+' );
1253 }
1254 else {
1255 $self->die_or_warn("<$name> element has no '$key' key attribute");
1256 return ($arrayref);
1257 }
1258 }
1259 }
1260  
1261 # Or assume keyattr => [ .... ]
1262  
1263 else {
1264 my $default_keys = join( ',', @DefKeyAttr ) eq join( ',', @{ $self->{opt}->{keyattr} } );
1265  
1266 ELEMENT: for ( $i = 0; $i < @$arrayref; $i++ ) {
1267 return ($arrayref) unless ( UNIVERSAL::isa( $arrayref->[$i], 'HASH' ) );
1268  
1269 foreach $key ( @{ $self->{opt}->{keyattr} } ) {
1270 if ( defined( $arrayref->[$i]->{$key} ) ) {
1271 $val = $arrayref->[$i]->{$key};
1272 if ( ref($val) ) {
1273 $self->die_or_warn("<$name> element has non-scalar '$key' key attribute")
1274 if not $default_keys;
1275 return ($arrayref);
1276 }
1277 $val = $self->normalise_space($val)
1278 if ( $self->{opt}->{normalisespace} == 1 );
1279 $self->die_or_warn("<$name> element has non-unique value in '$key' key attribute: $val")
1280 if ( exists( $hashref->{$val} ) );
1281 $hashref->{$val} = $self->new_hashref( %{ $arrayref->[$i] } );
1282 delete $hashref->{$val}->{$key};
1283 next ELEMENT;
1284 }
1285 }
1286  
1287 return ($arrayref); # No keyfield matched
1288 }
1289 }
1290  
1291 # collapse any hashes which now only have a 'content' key
1292  
1293 if ( $self->{opt}->{collapseagain} ) {
1294 $hashref = $self->collapse_content($hashref);
1295 }
1296  
1297 return ($hashref);
1298 }
1299  
1300 ##############################################################################
1301 # Method: die_or_warn()
1302 #
1303 # Takes a diagnostic message and does one of three things:
1304 # 1. dies if strict mode is enabled
1305 # 2. warns if warnings are enabled but strict mode is not
1306 # 3. ignores message and returns silently if neither strict mode nor warnings
1307 # are enabled
1308 #
1309  
1310 sub die_or_warn {
1311 my $self = shift;
1312 my $msg = shift;
1313  
1314 croak $msg if ( $self->{opt}->{strictmode} );
1315 if ( warnings::enabled() ) {
1316 carp "Warning: $msg";
1317 }
1318 }
1319  
1320 ##############################################################################
1321 # Method: new_hashref()
1322 #
1323 # This is a hook routine for overriding in a sub-class. Some people believe
1324 # that using Tie::IxHash here will solve order-loss problems.
1325 #
1326  
1327 sub new_hashref {
1328 my $self = shift;
1329  
1330 return {@_};
1331 }
1332  
1333 ##############################################################################
1334 # Method: collapse_content()
1335 #
1336 # Helper routine for array_to_hash
1337 #
1338 # Arguments expected are:
1339 # - an XML::Simple object
1340 # - a hashref
1341 # the hashref is a former array, turned into a hash by array_to_hash because
1342 # of the presence of key attributes
1343 # at this point collapse_content avoids over-complicated structures like
1344 # dir => { libexecdir => { content => '$exec_prefix/libexec' },
1345 # localstatedir => { content => '$prefix' },
1346 # }
1347 # into
1348 # dir => { libexecdir => '$exec_prefix/libexec',
1349 # localstatedir => '$prefix',
1350 # }
1351  
1352 sub collapse_content {
1353 my $self = shift;
1354 my $hashref = shift;
1355  
1356 my $contentkey = $self->{opt}->{contentkey};
1357  
1358 # first go through the values,checking that they are fit to collapse
1359 foreach my $val ( values %$hashref ) {
1360 return $hashref unless ( ( ref($val) eq 'HASH' )
1361 and ( keys %$val == 1 )
1362 and ( exists $val->{$contentkey} ) );
1363 }
1364  
1365 # now collapse them
1366 foreach my $key ( keys %$hashref ) {
1367 $hashref->{$key} = $hashref->{$key}->{$contentkey};
1368 }
1369  
1370 return $hashref;
1371 }
1372  
1373 ##############################################################################
1374 # Method: value_to_xml()
1375 #
1376 # Helper routine for XMLout() - recurses through a data structure building up
1377 # and returning an XML representation of that structure as a string.
1378 #
1379 # Arguments expected are:
1380 # - the data structure to be encoded (usually a reference)
1381 # - the XML tag name to use for this item
1382 # - a string of spaces for use as the current indent level
1383 #
1384  
1385 sub value_to_xml {
1386 my $self = shift;
1387  
1388 # Grab the other arguments
1389  
1390 my ( $ref, $name, $indent ) = @_;
1391  
1392 my $named = ( defined($name) and $name ne '' ? 1 : 0 );
1393  
1394 my $nl = "\n";
1395  
1396 my $is_root = $indent eq '' ? 1 : 0; # Warning, dirty hack!
1397 if ( $self->{opt}->{noindent} ) {
1398 $indent = '';
1399 $nl = '';
1400 }
1401  
1402 # Convert to XML
1403  
1404 my $refaddr = Scalar::Util::refaddr($ref);
1405 if ($refaddr) {
1406 croak "circular data structures not supported"
1407 if $self->{_ancestors}->{$refaddr};
1408 $self->{_ancestors}->{$refaddr} = $ref; # keep ref alive until we delete it
1409 }
1410 else {
1411 if ($named) {
1412 return (
1413 join( '',
1414 $indent, '<', $name, '>', ( $self->{opt}->{noescape} ? $ref : $self->escape_value($ref) ),
1415 '</', $name, ">", $nl )
1416 );
1417 }
1418 else {
1419 return ("$ref$nl");
1420 }
1421 }
1422  
1423 # Unfold hash to array if possible
1424  
1425 if (
1426 UNIVERSAL::isa( $ref, 'HASH' ) # It is a hash
1427 and keys %$ref # and it's not empty
1428 and $self->{opt}->{keyattr} # and folding is enabled
1429 and !$is_root # and its not the root element
1430 ) {
1431 $ref = $self->hash_to_array( $name, $ref );
1432 }
1433  
1434 my @result = ();
1435 my ( $key, $value );
1436  
1437 # Handle hashrefs
1438  
1439 if ( UNIVERSAL::isa( $ref, 'HASH' ) ) {
1440  
1441 # Reintermediate grouped values if applicable
1442  
1443 if ( $self->{opt}->{grouptags} ) {
1444 $ref = $self->copy_hash($ref);
1445 while ( my ( $key, $val ) = each %$ref ) {
1446 if ( $self->{opt}->{grouptags}->{$key} ) {
1447 $ref->{$key} = $self->new_hashref( $self->{opt}->{grouptags}->{$key} => $val );
1448 }
1449 }
1450 }
1451  
1452 # Scan for namespace declaration attributes
1453  
1454 my $nsdecls = '';
1455 my $default_ns_uri;
1456 if ( $self->{nsup} ) {
1457 $ref = $self->copy_hash($ref);
1458 $self->{nsup}->push_context();
1459  
1460 # Look for default namespace declaration first
1461  
1462 if ( exists( $ref->{xmlns} ) ) {
1463 $self->{nsup}->declare_prefix( '', $ref->{xmlns} );
1464 $nsdecls .= qq( xmlns="$ref->{xmlns}");
1465 delete( $ref->{xmlns} );
1466 }
1467 $default_ns_uri = $self->{nsup}->get_uri('');
1468  
1469 # Then check all the other keys
1470  
1471 foreach my $qname ( keys(%$ref) ) {
1472 my ( $uri, $lname ) = $self->{nsup}->parse_jclark_notation($qname);
1473 if ($uri) {
1474 if ( $uri eq $xmlns_ns ) {
1475 $self->{nsup}->declare_prefix( $lname, $ref->{$qname} );
1476 $nsdecls .= qq( xmlns:$lname="$ref->{$qname}");
1477 delete( $ref->{$qname} );
1478 }
1479 }
1480 }
1481  
1482 # Translate any remaining Clarkian names
1483  
1484 foreach my $qname ( keys(%$ref) ) {
1485 my ( $uri, $lname ) = $self->{nsup}->parse_jclark_notation($qname);
1486 if ($uri) {
1487 if ( $default_ns_uri and $uri eq $default_ns_uri ) {
1488 $ref->{$lname} = $ref->{$qname};
1489 delete( $ref->{$qname} );
1490 }
1491 else {
1492 my $prefix = $self->{nsup}->get_prefix($uri);
1493 unless ($prefix) {
1494 # $self->{nsup}->declare_prefix(undef, $uri);
1495 # $prefix = $self->{nsup}->get_prefix($uri);
1496 $prefix = $self->{ns_prefix}++;
1497 $self->{nsup}->declare_prefix( $prefix, $uri );
1498 $nsdecls .= qq( xmlns:$prefix="$uri");
1499 }
1500 $ref->{"$prefix:$lname"} = $ref->{$qname};
1501 delete( $ref->{$qname} );
1502 }
1503 }
1504 }
1505 }
1506  
1507 my @nested = ();
1508 my $text_content = undef;
1509 if ($named) {
1510 push @result, $indent, '<', $name, $nsdecls;
1511 }
1512  
1513 if ( keys %$ref ) {
1514 my $first_arg = 1;
1515 foreach my $key ( $self->sorted_keys( $name, $ref ) ) {
1516 my $value = $ref->{$key};
1517 next if ( substr( $key, 0, 1 ) eq '-' );
1518 if ( !defined($value) ) {
1519 next if $self->{opt}->{suppressempty};
1520 unless ( exists( $self->{opt}->{suppressempty} )
1521 and !defined( $self->{opt}->{suppressempty} ) ) {
1522 carp 'Use of uninitialized value' if warnings::enabled();
1523 }
1524 if ( $key eq $self->{opt}->{contentkey} ) {
1525 $text_content = '';
1526 }
1527 else {
1528 $value = exists( $self->{opt}->{suppressempty} ) ? {} : '';
1529 }
1530 }
1531  
1532 if ( !ref($value)
1533 and $self->{opt}->{valueattr}
1534 and $self->{opt}->{valueattr}->{$key} ) {
1535 $value = $self->new_hashref( $self->{opt}->{valueattr}->{$key} => $value );
1536 }
1537  
1538 if ( ref($value) or $self->{opt}->{noattr} ) {
1539 push @nested, $self->value_to_xml( $value, $key, "$indent " );
1540 }
1541 else {
1542 if ( $key eq $self->{opt}->{contentkey} ) {
1543 $value = $self->escape_value($value) unless ( $self->{opt}->{noescape} );
1544 $text_content = $value;
1545 }
1546 else {
1547 $value = $self->escape_attr($value) unless ( $self->{opt}->{noescape} );
1548 push @result, "\n$indent " . ' ' x length($name)
1549 if ( $self->{opt}->{attrindent} and !$first_arg );
1550 push @result, ' ', $key, '="', $value, '"';
1551 $first_arg = 0;
1552 }
1553 }
1554 }
1555 }
1556 else {
1557 $text_content = '';
1558 }
1559  
1560 if ( @nested or defined($text_content) ) {
1561 if ($named) {
1562 push @result, ">";
1563 if ( defined($text_content) ) {
1564 push @result, $text_content;
1565 $nested[0] =~ s/^\s+// if (@nested);
1566 }
1567 else {
1568 push @result, $nl;
1569 }
1570 if (@nested) {
1571 push @result, @nested, $indent;
1572 }
1573 push @result, '</', $name, ">", $nl;
1574 }
1575 else {
1576 push @result, @nested; # Special case if no root elements
1577 }
1578 }
1579 else {
1580 push @result, " />", $nl;
1581 }
1582 $self->{nsup}->pop_context() if ( $self->{nsup} );
1583 }
1584  
1585 # Handle arrayrefs
1586  
1587 elsif ( UNIVERSAL::isa( $ref, 'ARRAY' ) ) {
1588 foreach $value (@$ref) {
1589 next if !defined($value) and $self->{opt}->{suppressempty};
1590 if ( !ref($value) ) {
1591 push @result,
1592 $indent, '<', $name, '>',
1593 ( $self->{opt}->{noescape} ? $value : $self->escape_value($value) ),
1594 '</', $name, ">$nl";
1595 }
1596 elsif ( UNIVERSAL::isa( $value, 'HASH' ) ) {
1597 push @result, $self->value_to_xml( $value, $name, $indent );
1598 }
1599 else {
1600 push @result,
1601 $indent, '<', $name, ">$nl",
1602 $self->value_to_xml( $value, 'anon', "$indent " ),
1603 $indent, '</', $name, ">$nl";
1604 }
1605 }
1606 }
1607  
1608 else {
1609 croak "Can't encode a value of type: " . ref($ref);
1610 }
1611  
1612 delete $self->{_ancestors}->{$refaddr};
1613  
1614 return ( join( '', @result ) );
1615 }
1616  
1617 ##############################################################################
1618 # Method: sorted_keys()
1619 #
1620 # Returns the keys of the referenced hash sorted into alphabetical order, but
1621 # with the 'key' key (as in KeyAttr) first, if there is one.
1622 #
1623  
1624 sub sorted_keys {
1625 my ( $self, $name, $ref ) = @_;
1626  
1627 return keys %$ref if $self->{opt}->{nosort};
1628  
1629 my %hash = %$ref;
1630 my $keyattr = $self->{opt}->{keyattr};
1631  
1632 my @key;
1633  
1634 if ( ref $keyattr eq 'HASH' ) {
1635 if ( exists $keyattr->{$name} and exists $hash{ $keyattr->{$name}->[0] } ) {
1636 push @key, $keyattr->{$name}->[0];
1637 delete $hash{ $keyattr->{$name}->[0] };
1638 }
1639 }
1640 elsif ( ref $keyattr eq 'ARRAY' ) {
1641 foreach ( @{$keyattr} ) {
1642 if ( exists $hash{$_} ) {
1643 push @key, $_;
1644 delete $hash{$_};
1645 last;
1646 }
1647 }
1648 }
1649  
1650 return ( @key, sort keys %hash );
1651 }
1652  
1653 ##############################################################################
1654 # Method: escape_value()
1655 #
1656 # Helper routine for automatically escaping values for XMLout().
1657 # Expects a scalar data value. Returns escaped version.
1658 #
1659  
1660 sub escape_value {
1661 my ( $self, $data ) = @_;
1662  
1663 return '' unless ( defined($data) );
1664  
1665 $data =~ s/&/&amp;/sg;
1666 $data =~ s/</&lt;/sg;
1667 $data =~ s/>/&gt;/sg;
1668 $data =~ s/"/&quot;/sg;
1669  
1670 my $level = $self->{opt}->{numericescape} or return $data;
1671  
1672 return $self->numeric_escape( $data, $level );
1673 }
1674  
1675 sub numeric_escape {
1676 my ( $self, $data, $level ) = @_;
1677  
1678 if ( $self->{opt}->{numericescape} eq '2' ) {
1679 $data =~ s/([^\x00-\x7F])/'&#' . ord($1) . ';'/gse;
1680 }
1681 else {
1682 $data =~ s/([^\x00-\xFF])/'&#' . ord($1) . ';'/gse;
1683 }
1684  
1685 return $data;
1686 }
1687  
1688 ##############################################################################
1689 # Method: escape_attr()
1690 #
1691 # Helper routine for escaping attribute values. Defaults to escape_value(),
1692 # but may be overridden by a subclass to customise behaviour.
1693 #
1694  
1695 sub escape_attr {
1696 my $self = shift;
1697  
1698 return $self->escape_value(@_);
1699 }
1700  
1701 ##############################################################################
1702 # Method: hash_to_array()
1703 #
1704 # Helper routine for value_to_xml().
1705 # Attempts to 'unfold' a hash of hashes into an array of hashes. Returns a
1706 # reference to the array on success or the original hash if unfolding is
1707 # not possible.
1708 #
1709  
1710 sub hash_to_array {
1711 my $self = shift;
1712 my $parent = shift;
1713 my $hashref = shift;
1714  
1715 my $arrayref = [];
1716  
1717 my ( $key, $value );
1718  
1719 my @keys = $self->{opt}->{nosort} ? keys %$hashref : sort keys %$hashref;
1720 foreach $key (@keys) {
1721 $value = $hashref->{$key};
1722 return ($hashref) unless ( UNIVERSAL::isa( $value, 'HASH' ) );
1723  
1724 if ( ref( $self->{opt}->{keyattr} ) eq 'HASH' ) {
1725 return ($hashref) unless ( defined( $self->{opt}->{keyattr}->{$parent} ) );
1726 push @$arrayref, $self->copy_hash( $value, $self->{opt}->{keyattr}->{$parent}->[0] => $key );
1727 }
1728 else {
1729 push( @$arrayref, { $self->{opt}->{keyattr}->[0] => $key, %$value } );
1730 }
1731 }
1732  
1733 return ($arrayref);
1734 }
1735  
1736 ##############################################################################
1737 # Method: copy_hash()
1738 #
1739 # Helper routine for hash_to_array(). When unfolding a hash of hashes into
1740 # an array of hashes, we need to copy the key from the outer hash into the
1741 # inner hash. This routine makes a copy of the original hash so we don't
1742 # destroy the original data structure. You might wish to override this
1743 # method if you're using tied hashes and don't want them to get untied.
1744 #
1745  
1746 sub copy_hash {
1747 my ( $self, $orig, @extra ) = @_;
1748  
1749 return { @extra, %$orig };
1750 }
1751  
1752 ##############################################################################
1753 # Methods required for building trees from SAX events
1754 ##############################################################################
1755  
1756 sub start_document {
1757 my $self = shift;
1758  
1759 $self->handle_options('in') unless ( $self->{opt} );
1760  
1761 $self->{lists} = [];
1762 $self->{curlist} = $self->{tree} = [];
1763 }
1764  
1765 sub start_element {
1766 my $self = shift;
1767 my $element = shift;
1768  
1769 my $name = $element->{Name};
1770 if ( $self->{opt}->{nsexpand} ) {
1771 $name = $element->{LocalName} || '';
1772 if ( $element->{NamespaceURI} ) {
1773 $name = '{' . $element->{NamespaceURI} . '}' . $name;
1774 }
1775 }
1776 my $attributes = {};
1777 if ( $element->{Attributes} ) { # Might be undef
1778 foreach my $attr ( values %{ $element->{Attributes} } ) {
1779 if ( $self->{opt}->{nsexpand} ) {
1780 my $name = $attr->{LocalName} || '';
1781 if ( $attr->{NamespaceURI} ) {
1782 $name = '{' . $attr->{NamespaceURI} . '}' . $name;
1783 }
1784 $name = 'xmlns' if ( $name eq $bad_def_ns_jcn );
1785 $attributes->{$name} = $attr->{Value};
1786 }
1787 else {
1788 $attributes->{ $attr->{Name} } = $attr->{Value};
1789 }
1790 }
1791 }
1792 my $newlist = [$attributes];
1793 push @{ $self->{lists} }, $self->{curlist};
1794 push @{ $self->{curlist} }, $name => $newlist;
1795 $self->{curlist} = $newlist;
1796 }
1797  
1798 sub characters {
1799 my $self = shift;
1800 my $chars = shift;
1801  
1802 my $text = $chars->{Data};
1803 my $clist = $self->{curlist};
1804 my $pos = $#$clist;
1805  
1806 if ( $pos > 0 and $clist->[ $pos - 1 ] eq '0' ) {
1807 $clist->[$pos] .= $text;
1808 }
1809 else {
1810 push @$clist, 0 => $text;
1811 }
1812 }
1813  
1814 sub end_element {
1815 my $self = shift;
1816  
1817 $self->{curlist} = pop @{ $self->{lists} };
1818 }
1819  
1820 sub end_document {
1821 my $self = shift;
1822  
1823 delete( $self->{curlist} );
1824 delete( $self->{lists} );
1825  
1826 my $tree = $self->{tree};
1827 delete( $self->{tree} );
1828  
1829 # Return tree as-is to XMLin()
1830  
1831 return ($tree) if ( $self->{nocollapse} );
1832  
1833 # Or collapse it before returning it to SAX parser class
1834  
1835 if ( $self->{opt}->{keeproot} ) {
1836 $tree = $self->collapse( {}, @$tree );
1837 }
1838 else {
1839 $tree = $self->collapse( @{ $tree->[1] } );
1840 }
1841  
1842 if ( $self->{opt}->{datahandler} ) {
1843 return ( $self->{opt}->{datahandler}->( $self, $tree ) );
1844 }
1845  
1846 return ($tree);
1847 }
1848  
1849 *xml_in = \&XMLin;
1850 *xml_out = \&XMLout;
1851  
1852 1;
1853  
1854 __END__