home *** CD-ROM | disk | FTP | other *** search
/ Netrunner 2004 October / NETRUNNER0410.ISO / regular / ActivePerl-5.8.4.810-MSWin32-x86.msi / _b6adf8023f85b0a7f12e7120cda7402d < prev    next >
Text File  |  2004-06-01  |  91KB  |  3,009 lines

  1. # $Id: Simple.pm,v 1.20 2004/04/05 09:12:47 grantm Exp $
  2.  
  3. package XML::Simple;
  4.  
  5. =head1 NAME
  6.  
  7. XML::Simple - Easy API to maintain XML (esp config files)
  8.  
  9. =head1 SYNOPSIS
  10.  
  11.     use XML::Simple;
  12.  
  13.     my $ref = XMLin([<xml file or string>] [, <options>]);
  14.  
  15.     my $xml = XMLout($hashref [, <options>]);
  16.  
  17. Or the object oriented way:
  18.  
  19.     require XML::Simple;
  20.  
  21.     my $xs = new XML::Simple(options);
  22.  
  23.     my $ref = $xs->XMLin([<xml file or string>] [, <options>]);
  24.  
  25.     my $xml = $xs->XMLout($hashref [, <options>]);
  26.  
  27. (or see L<"SAX SUPPORT"> for 'the SAX way').
  28.  
  29. To catch common errors:
  30.  
  31.     use XML::Simple qw(:strict);
  32.  
  33. (see L<"STRICT MODE"> for more details).
  34.  
  35. =cut
  36.  
  37. # See after __END__ for more POD documentation
  38.  
  39.  
  40. # Load essentials here, other modules loaded on demand later
  41.  
  42. use strict;
  43. use Carp;
  44. require Exporter;
  45.  
  46.  
  47. ##############################################################################
  48. # Define some constants
  49. #
  50.  
  51. use vars qw($VERSION @ISA @EXPORT @EXPORT_OK $PREFERRED_PARSER);
  52.  
  53. @ISA               = qw(Exporter);
  54. @EXPORT            = qw(XMLin XMLout);
  55. @EXPORT_OK         = qw(xml_in xml_out);
  56. $VERSION           = '2.12';
  57. $PREFERRED_PARSER  = undef;
  58.  
  59. my $StrictMode     = 0;
  60. my %CacheScheme    = (
  61.                        storable => [ \&StorableSave, \&StorableRestore ],
  62.                        memshare => [ \&MemShareSave, \&MemShareRestore ],
  63.                        memcopy  => [ \&MemCopySave,  \&MemCopyRestore  ]
  64.                      );
  65.  
  66. my @KnownOptIn     = qw(keyattr keeproot forcecontent contentkey noattr
  67.                         searchpath forcearray cache suppressempty parseropts
  68.                         grouptags nsexpand datahandler varattr variables
  69.                         normalisespace normalizespace valueattr);
  70.  
  71. my @KnownOptOut    = qw(keyattr keeproot contentkey noattr
  72.                         rootname xmldecl outputfile noescape suppressempty
  73.                         grouptags nsexpand handler noindent attrindent nosort
  74.                         valueattr numericescape);
  75.  
  76. my @DefKeyAttr     = qw(name key id);
  77. my $DefRootName    = qq(opt);
  78. my $DefContentKey  = qq(content);
  79. my $DefXmlDecl     = qq(<?xml version='1.0' standalone='yes'?>);
  80.  
  81. my $xmlns_ns       = 'http://www.w3.org/2000/xmlns/';
  82. my $bad_def_ns_jcn = '{' . $xmlns_ns . '}';     # LibXML::SAX workaround
  83.  
  84.  
  85. ##############################################################################
  86. # Globals for use by caching routines
  87. #
  88.  
  89. my %MemShareCache  = ();
  90. my %MemCopyCache   = ();
  91.  
  92.  
  93. ##############################################################################
  94. # Wrapper for Exporter - handles ':strict'
  95. #
  96.  
  97. sub import {
  98.  
  99.   # Handle the :strict tag
  100.   
  101.   $StrictMode = 1 if grep(/^:strict$/, @_);
  102.  
  103.   # Pass everything else to Exporter.pm
  104.  
  105.   __PACKAGE__->export_to_level(1, grep(!/^:strict$/, @_));
  106. }
  107.  
  108.  
  109. ##############################################################################
  110. # Constructor for optional object interface.
  111. #
  112.  
  113. sub new {
  114.   my $class = shift;
  115.  
  116.   if(@_ % 2) {
  117.     croak "Default options must be name=>value pairs (odd number supplied)";
  118.   }
  119.  
  120.   my %known_opt;
  121.   @known_opt{@KnownOptIn, @KnownOptOut} = (undef) x 100;
  122.  
  123.   my %raw_opt = @_;
  124.   my %def_opt;
  125.   while(my($key, $val) = each %raw_opt) {
  126.     my $lkey = lc($key);
  127.     $lkey =~ s/_//g;
  128.     croak "Unrecognised option: $key" unless(exists($known_opt{$lkey}));
  129.     $def_opt{$lkey} = $val;
  130.   }
  131.   my $self = { def_opt => \%def_opt };
  132.  
  133.   return(bless($self, $class));
  134. }
  135.  
  136.  
  137. ##############################################################################
  138. # Sub/Method: XMLin()
  139. #
  140. # Exported routine for slurping XML into a hashref - see pod for info.
  141. #
  142. # May be called as object method or as a plain function.
  143. #
  144. # Expects one arg for the source XML, optionally followed by a number of
  145. # name => value option pairs.
  146. #
  147.  
  148. sub XMLin {
  149.  
  150.   # If this is not a method call, create an object
  151.  
  152.   my $self;
  153.   if($_[0]  and  UNIVERSAL::isa($_[0], 'XML::Simple')) {
  154.     $self = shift;
  155.   }
  156.   else {
  157.     $self = new XML::Simple();
  158.   }
  159.  
  160.  
  161.   my $string = shift;
  162.  
  163.   $self->handle_options('in', @_);
  164.  
  165.  
  166.   # If no XML or filename supplied, look for scriptname.xml in script directory
  167.  
  168.   unless(defined($string))  {
  169.     
  170.     # Translate scriptname[.suffix] to scriptname.xml
  171.  
  172.     require File::Basename;
  173.  
  174.     my($ScriptName, $ScriptDir, $Extension) =
  175.       File::Basename::fileparse($0, '\.[^\.]+');
  176.  
  177.     $string = $ScriptName . '.xml';
  178.  
  179.  
  180.     # Add script directory to searchpath
  181.     
  182.     if($ScriptDir) {
  183.       unshift(@{$self->{opt}->{searchpath}}, $ScriptDir);
  184.     }
  185.   }
  186.   
  187.  
  188.   # Are we parsing from a file?  If so, is there a valid cache available?
  189.  
  190.   my($filename, $scheme);
  191.   unless($string =~ m{<.*?>}s  or  ref($string)  or  $string eq '-') {
  192.  
  193.     require File::Basename;
  194.     require File::Spec;
  195.  
  196.     $filename = $self->find_xml_file($string, @{$self->{opt}->{searchpath}});
  197.  
  198.     if($self->{opt}->{cache}) {
  199.       foreach $scheme (@{$self->{opt}->{cache}}) {
  200.         croak "Unsupported caching scheme: $scheme"
  201.           unless($CacheScheme{$scheme});
  202.  
  203.         my $opt = $CacheScheme{$scheme}->[1]->($filename);
  204.         return($opt) if($opt);
  205.       }
  206.     }
  207.   }
  208.   else {
  209.     delete($self->{opt}->{cache});
  210.     if($string eq '-') {
  211.       # Read from standard input
  212.  
  213.       local($/) = undef;
  214.       $string = <STDIN>;
  215.     }
  216.   }
  217.  
  218.  
  219.   # Parsing is required, so let's get on with it
  220.  
  221.   my $tree =  $self->build_tree($filename, $string);
  222.  
  223.  
  224.   # Now work some magic on the resulting parse tree
  225.  
  226.   my($ref);
  227.   if($self->{opt}->{keeproot}) {
  228.     $ref = $self->collapse({}, @$tree);
  229.   }
  230.   else {
  231.     $ref = $self->collapse(@{$tree->[1]});
  232.   }
  233.  
  234.   if($self->{opt}->{cache}) {
  235.     $CacheScheme{$self->{opt}->{cache}->[0]}->[0]->($ref, $filename);
  236.   }
  237.  
  238.   return($ref);
  239. }
  240.  
  241.  
  242. ##############################################################################
  243. # Method: build_tree()
  244. #
  245. # This routine will be called if there is no suitable pre-parsed tree in a
  246. # cache.  It parses the XML and returns an XML::Parser 'Tree' style data
  247. # structure (summarised in the comments for the collapse() routine below).
  248. #
  249. # XML::Simple requires the services of another module that knows how to
  250. # parse XML.  If XML::SAX is installed, the default SAX parser will be used,
  251. # otherwise XML::Parser will be used.
  252. #
  253. # This routine expects to be passed a 'string' as argument 1 or a filename as
  254. # argument 2.  The 'string' might be a string of XML or it might be a 
  255. # reference to an IO::Handle.  (This non-intuitive mess results in part from
  256. # the way XML::Parser works but that's really no excuse).
  257. #
  258.  
  259. sub build_tree {
  260.   my $self     = shift;
  261.   my $filename = shift;
  262.   my $string   = shift;
  263.  
  264.  
  265.   my $preferred_parser = $PREFERRED_PARSER;
  266.   unless(defined($preferred_parser)) {
  267.     $preferred_parser = $ENV{XML_SIMPLE_PREFERRED_PARSER} || '';
  268.   }
  269.   if($preferred_parser eq 'XML::Parser') {
  270.     return($self->build_tree_xml_parser($filename, $string));
  271.   }
  272.  
  273.   eval { require XML::SAX; };      # We didn't need it until now
  274.   if($@) {                         # No XML::SAX - fall back to XML::Parser
  275.     if($preferred_parser) {        # unless a SAX parser was expressly requested
  276.       croak "XMLin() could not load XML::SAX";
  277.     }
  278.     return($self->build_tree_xml_parser($filename, $string));
  279.   }
  280.  
  281.   $XML::SAX::ParserPackage = $preferred_parser if($preferred_parser);
  282.  
  283.   my $sp = XML::SAX::ParserFactory->parser(Handler => $self);
  284.   
  285.   $self->{nocollapse} = 1;
  286.   my($tree);
  287.   if($filename) {
  288.     $tree = $sp->parse_uri($filename);
  289.   }
  290.   else {
  291.     if(ref($string)) {
  292.       $tree = $sp->parse_file($string);
  293.     }
  294.     else {
  295.       $tree = $sp->parse_string($string);
  296.     }
  297.   }
  298.  
  299.   return($tree);
  300. }
  301.  
  302.  
  303. ##############################################################################
  304. # Method: build_tree_xml_parser()
  305. #
  306. # This routine will be called if XML::SAX is not installed, or if XML::Parser
  307. # was specifically requested.  It takes the same arguments as build_tree() and
  308. # returns the same data structure (XML::Parser 'Tree' style).
  309. #
  310.  
  311. sub build_tree_xml_parser {
  312.   my $self     = shift;
  313.   my $filename = shift;
  314.   my $string   = shift;
  315.  
  316.  
  317.   eval {
  318.     local($^W) = 0;      # Suppress warning from Expat.pm re File::Spec::load()
  319.     require XML::Parser; # We didn't need it until now
  320.   };
  321.   if($@) {
  322.     croak "XMLin() requires either XML::SAX or XML::Parser";
  323.   }
  324.  
  325.   if($self->{opt}->{nsexpand}) {
  326.     carp "'nsexpand' option requires XML::SAX";
  327.   }
  328.  
  329.   my $xp = new XML::Parser(Style => 'Tree', @{$self->{opt}->{parseropts}});
  330.   my($tree);
  331.   if($filename) {
  332.     # $tree = $xp->parsefile($filename);  # Changed due to prob w/mod_perl
  333.     local(*XML_FILE);
  334.     open(XML_FILE, '<', $filename) || croak qq($filename - $!);
  335.     $tree = $xp->parse(*XML_FILE);
  336.     close(XML_FILE);
  337.   }
  338.   else {
  339.     $tree = $xp->parse($string);
  340.   }
  341.  
  342.   return($tree);
  343. }
  344.  
  345.  
  346. ##############################################################################
  347. # Sub: StorableSave()
  348. #
  349. # Wrapper routine for invoking Storable::nstore() to cache a parsed data
  350. # structure.
  351. #
  352.  
  353. sub StorableSave {
  354.   my($data, $filename) = @_;
  355.  
  356.   my $cachefile = $filename;
  357.   $cachefile =~ s{(\.xml)?$}{.stor};
  358.  
  359.   require Storable;           # We didn't need it until now
  360.  
  361.   # If the following line fails for you, your Storable.pm is old - upgrade
  362.   
  363.   Storable::lock_nstore($data, $cachefile);
  364.   
  365. }
  366.  
  367.  
  368. ##############################################################################
  369. # Sub: StorableRestore()
  370. #
  371. # Wrapper routine for invoking Storable::retrieve() to read a cached parsed
  372. # data structure.  Only returns cached data if the cache file exists and is
  373. # newer than the source XML file.
  374. #
  375.  
  376. sub StorableRestore {
  377.   my($filename) = @_;
  378.   
  379.   my $cachefile = $filename;
  380.   $cachefile =~ s{(\.xml)?$}{.stor};
  381.  
  382.   return unless(-r $cachefile);
  383.   return unless((stat($cachefile))[9] > (stat($filename))[9]);
  384.  
  385.   require Storable;           # We didn't need it until now
  386.   
  387.   return(Storable::lock_retrieve($cachefile));
  388.   
  389. }
  390.  
  391.  
  392. ##############################################################################
  393. # Sub: MemShareSave()
  394. #
  395. # Takes the supplied data structure reference and stores it away in a global
  396. # hash structure.
  397. #
  398.  
  399. sub MemShareSave {
  400.   my($data, $filename) = @_;
  401.  
  402.   $MemShareCache{$filename} = [time(), $data];
  403. }
  404.  
  405.  
  406. ##############################################################################
  407. # Sub: MemShareRestore()
  408. #
  409. # Takes a filename and looks in a global hash for a cached parsed version.
  410. #
  411.  
  412. sub MemShareRestore {
  413.   my($filename) = @_;
  414.   
  415.   return unless($MemShareCache{$filename});
  416.   return unless($MemShareCache{$filename}->[0] > (stat($filename))[9]);
  417.  
  418.   return($MemShareCache{$filename}->[1]);
  419.   
  420. }
  421.  
  422.  
  423. ##############################################################################
  424. # Sub: MemCopySave()
  425. #
  426. # Takes the supplied data structure and stores a copy of it in a global hash
  427. # structure.
  428. #
  429.  
  430. sub MemCopySave {
  431.   my($data, $filename) = @_;
  432.  
  433.   require Storable;           # We didn't need it until now
  434.   
  435.   $MemCopyCache{$filename} = [time(), Storable::dclone($data)];
  436. }
  437.  
  438.  
  439. ##############################################################################
  440. # Sub: MemCopyRestore()
  441. #
  442. # Takes a filename and looks in a global hash for a cached parsed version.
  443. # Returns a reference to a copy of that data structure.
  444. #
  445.  
  446. sub MemCopyRestore {
  447.   my($filename) = @_;
  448.   
  449.   return unless($MemCopyCache{$filename});
  450.   return unless($MemCopyCache{$filename}->[0] > (stat($filename))[9]);
  451.  
  452.   return(Storable::dclone($MemCopyCache{$filename}->[1]));
  453.   
  454. }
  455.  
  456.  
  457. ##############################################################################
  458. # Sub/Method: XMLout()
  459. #
  460. # Exported routine for 'unslurping' a data structure out to XML.
  461. #
  462. # Expects a reference to a data structure and an optional list of option
  463. # name => value pairs.
  464. #
  465.  
  466. sub XMLout {
  467.  
  468.   # If this is not a method call, create an object
  469.  
  470.   my $self;
  471.   if($_[0]  and  UNIVERSAL::isa($_[0], 'XML::Simple')) {
  472.     $self = shift;
  473.   }
  474.   else {
  475.     $self = new XML::Simple();
  476.   }
  477.  
  478.   croak "XMLout() requires at least one argument" unless(@_);
  479.   my $ref = shift;
  480.  
  481.   $self->handle_options('out', @_);
  482.  
  483.  
  484.   # If namespace expansion is set, XML::NamespaceSupport is required
  485.  
  486.   if($self->{opt}->{nsexpand}) {
  487.     require XML::NamespaceSupport;
  488.     $self->{nsup} = XML::NamespaceSupport->new();
  489.     $self->{ns_prefix} = 'aaa';
  490.   }
  491.  
  492.  
  493.   # Wrap top level arrayref in a hash
  494.  
  495.   if(UNIVERSAL::isa($ref, 'ARRAY')) {
  496.     $ref = { anon => $ref };
  497.   }
  498.  
  499.  
  500.   # Extract rootname from top level hash if keeproot enabled
  501.  
  502.   if($self->{opt}->{keeproot}) {
  503.     my(@keys) = keys(%$ref);
  504.     if(@keys == 1) {
  505.       $ref = $ref->{$keys[0]};
  506.       $self->{opt}->{rootname} = $keys[0];
  507.     }
  508.   }
  509.   
  510.   # Ensure there are no top level attributes if we're not adding root elements
  511.  
  512.   elsif($self->{opt}->{rootname} eq '') {
  513.     if(UNIVERSAL::isa($ref, 'HASH')) {
  514.       my $refsave = $ref;
  515.       $ref = {};
  516.       foreach (keys(%$refsave)) {
  517.         if(ref($refsave->{$_})) {
  518.           $ref->{$_} = $refsave->{$_};
  519.         }
  520.         else {
  521.           $ref->{$_} = [ $refsave->{$_} ];
  522.         }
  523.       }
  524.     }
  525.   }
  526.  
  527.  
  528.   # Encode the hashref and write to file if necessary
  529.  
  530.   $self->{_ancestors} = [];
  531.   my $xml = $self->value_to_xml($ref, $self->{opt}->{rootname}, '');
  532.   delete $self->{_ancestors};
  533.  
  534.   if($self->{opt}->{xmldecl}) {
  535.     $xml = $self->{opt}->{xmldecl} . "\n" . $xml;
  536.   }
  537.  
  538.   if($self->{opt}->{outputfile}) {
  539.     if(ref($self->{opt}->{outputfile})) {
  540.       return($self->{opt}->{outputfile}->print($xml));
  541.     }
  542.     else {
  543.       local(*OUT);
  544.       open(OUT, '>', "$self->{opt}->{outputfile}") ||
  545.         croak "open($self->{opt}->{outputfile}): $!";
  546.       binmode(OUT, ':utf8') if($] >= 5.008);
  547.       print OUT $xml || croak "print: $!";
  548.       close(OUT);
  549.     }
  550.   }
  551.   elsif($self->{opt}->{handler}) {
  552.     require XML::SAX;
  553.     my $sp = XML::SAX::ParserFactory->parser(
  554.                Handler => $self->{opt}->{handler}
  555.              );
  556.     return($sp->parse_string($xml));
  557.   }
  558.   else {
  559.     return($xml);
  560.   }
  561. }
  562.  
  563.  
  564. ##############################################################################
  565. # Method: handle_options()
  566. #
  567. # Helper routine for both XMLin() and XMLout().  Both routines handle their
  568. # first argument and assume all other args are options handled by this routine.
  569. # Saves a hash of options in $self->{opt}.
  570. #
  571. # If default options were passed to the constructor, they will be retrieved
  572. # here and merged with options supplied to the method call.
  573. #
  574. # First argument should be the string 'in' or the string 'out'.
  575. #
  576. # Remaining arguments should be name=>value pairs.  Sets up default values
  577. # for options not supplied.  Unrecognised options are a fatal error.
  578. #
  579.  
  580. sub handle_options  {
  581.   my $self = shift;
  582.   my $dirn = shift;
  583.  
  584.  
  585.   # Determine valid options based on context
  586.  
  587.   my %known_opt; 
  588.   if($dirn eq 'in') {
  589.     @known_opt{@KnownOptIn} = @KnownOptIn;
  590.   }
  591.   else {
  592.     @known_opt{@KnownOptOut} = @KnownOptOut;
  593.   }
  594.  
  595.  
  596.   # Store supplied options in hashref and weed out invalid ones
  597.  
  598.   if(@_ % 2) {
  599.     croak "Options must be name=>value pairs (odd number supplied)";
  600.   }
  601.   my %raw_opt  = @_;
  602.   my $opt      = {};
  603.   $self->{opt} = $opt;
  604.  
  605.   while(my($key, $val) = each %raw_opt) {
  606.     my $lkey = lc($key);
  607.     $lkey =~ s/_//g;
  608.     croak "Unrecognised option: $key" unless($known_opt{$lkey});
  609.     $opt->{$lkey} = $val;
  610.   }
  611.  
  612.  
  613.   # Merge in options passed to constructor
  614.  
  615.   foreach (keys(%known_opt)) {
  616.     unless(exists($opt->{$_})) {
  617.       if(exists($self->{def_opt}->{$_})) {
  618.         $opt->{$_} = $self->{def_opt}->{$_};
  619.       }
  620.     }
  621.   }
  622.  
  623.  
  624.   # Set sensible defaults if not supplied
  625.   
  626.   if(exists($opt->{rootname})) {
  627.     unless(defined($opt->{rootname})) {
  628.       $opt->{rootname} = '';
  629.     }
  630.   }
  631.   else {
  632.     $opt->{rootname} = $DefRootName;
  633.   }
  634.   
  635.   if($opt->{xmldecl}  and  $opt->{xmldecl} eq '1') {
  636.     $opt->{xmldecl} = $DefXmlDecl;
  637.   }
  638.  
  639.   if(exists($opt->{contentkey})) {
  640.     if($opt->{contentkey} =~ m{^-(.*)$}) {
  641.       $opt->{contentkey} = $1;
  642.       $opt->{collapseagain} = 1;
  643.     }
  644.   }
  645.   else {
  646.     $opt->{contentkey} = $DefContentKey;
  647.   }
  648.  
  649.   unless(exists($opt->{normalisespace})) {
  650.     $opt->{normalisespace} = $opt->{normalizespace};
  651.   }
  652.   $opt->{normalisespace} = 0 unless(defined($opt->{normalisespace}));
  653.  
  654.   # Cleanups for values assumed to be arrays later
  655.  
  656.   if($opt->{searchpath}) {
  657.     unless(ref($opt->{searchpath})) {
  658.       $opt->{searchpath} = [ $opt->{searchpath} ];
  659.     }
  660.   }
  661.   else  {
  662.     $opt->{searchpath} = [ ];
  663.   }
  664.  
  665.   if($opt->{cache}  and !ref($opt->{cache})) {
  666.     $opt->{cache} = [ $opt->{cache} ];
  667.   }
  668.   if($opt->{cache}) {
  669.     $_ = lc($_) foreach (@{$opt->{cache}});
  670.   }
  671.   
  672.   if(exists($opt->{parseropts})) {
  673.     if($^W) {
  674.       carp "Warning: " .
  675.            "'ParserOpts' is deprecated, contact the author if you need it";
  676.     }
  677.   }
  678.   else {
  679.     $opt->{parseropts} = [ ];
  680.   }
  681.  
  682.   
  683.   # Special cleanup for {forcearray} which could be regex, arrayref or boolean
  684.   # or left to default to 0
  685.  
  686.   if(exists($opt->{forcearray})) {
  687.     if(ref($opt->{forcearray}) eq 'Regexp') {
  688.       $opt->{forcearray} = [ $opt->{forcearray} ];
  689.     }
  690.  
  691.     if(ref($opt->{forcearray}) eq 'ARRAY') {
  692.       my @force_list = @{$opt->{forcearray}};
  693.       if(@force_list) {
  694.         $opt->{forcearray} = {};
  695.         foreach my $tag (@force_list) {
  696.           if(ref($tag) eq 'Regexp') {
  697.             push @{$opt->{forcearray}->{_regex}}, $tag;
  698.           }
  699.           else {
  700.             $opt->{forcearray}->{$tag} = 1;
  701.           }
  702.         }
  703.       }
  704.       else {
  705.         $opt->{forcearray} = 0;
  706.       }
  707.     }
  708.     else {
  709.       $opt->{forcearray} = ( $opt->{forcearray} ? 1 : 0 );
  710.     }
  711.   }
  712.   else {
  713.     if($StrictMode  and  $dirn eq 'in') {
  714.       croak "No value specified for 'ForceArray' option in call to XML$dirn()";
  715.     }
  716.     $opt->{forcearray} = 0;
  717.   }
  718.  
  719.  
  720.   # Special cleanup for {keyattr} which could be arrayref or hashref or left
  721.   # to default to arrayref
  722.  
  723.   if(exists($opt->{keyattr}))  {
  724.     if(ref($opt->{keyattr})) {
  725.       if(ref($opt->{keyattr}) eq 'HASH') {
  726.  
  727.         # Make a copy so we can mess with it
  728.  
  729.         $opt->{keyattr} = { %{$opt->{keyattr}} };
  730.  
  731.         
  732.         # Convert keyattr => { elem => '+attr' }
  733.         # to keyattr => { elem => [ 'attr', '+' ] } 
  734.  
  735.         foreach my $el (keys(%{$opt->{keyattr}})) {
  736.           if($opt->{keyattr}->{$el} =~ /^(\+|-)?(.*)$/) {
  737.             $opt->{keyattr}->{$el} = [ $2, ($1 ? $1 : '') ];
  738.             if($StrictMode  and  $dirn eq 'in') {
  739.               next if($opt->{forcearray} == 1);
  740.               next if(ref($opt->{forcearray}) eq 'HASH'
  741.                       and $opt->{forcearray}->{$el});
  742.               croak "<$el> set in KeyAttr but not in ForceArray";
  743.             }
  744.           }
  745.           else {
  746.             delete($opt->{keyattr}->{$el}); # Never reached (famous last words?)
  747.           }
  748.         }
  749.       }
  750.       else {
  751.         if(@{$opt->{keyattr}} == 0) {
  752.           delete($opt->{keyattr});
  753.         }
  754.       }
  755.     }
  756.     else {
  757.       $opt->{keyattr} = [ $opt->{keyattr} ];
  758.     }
  759.   }
  760.   else  {
  761.     if($StrictMode) {
  762.       croak "No value specified for 'KeyAttr' option in call to XML$dirn()";
  763.     }
  764.     $opt->{keyattr} = [ @DefKeyAttr ];
  765.   }
  766.  
  767.  
  768.   # Special cleanup for {foldattr} which could be arrayref or hashref
  769.  
  770.   if(exists($opt->{valueattr})) {
  771.     if(ref($opt->{valueattr}) eq 'ARRAY') {
  772.       $opt->{valueattrlist} = {};
  773.       $opt->{valueattrlist}->{$_} = 1 foreach(@{ delete $opt->{valueattr} });
  774.     }
  775.   }
  776.  
  777.   # make sure there's nothing weird in {grouptags}
  778.  
  779.   if($opt->{grouptags} and !UNIVERSAL::isa($opt->{grouptags}, 'HASH')) {
  780.     croak "Illegal value for 'GroupTags' option - expected a hashref";
  781.   }
  782.  
  783.  
  784.   # Check the {variables} option is valid and initialise variables hash
  785.  
  786.   if($opt->{variables} and !UNIVERSAL::isa($opt->{variables}, 'HASH')) {
  787.     croak "Illegal value for 'Variables' option - expected a hashref";
  788.   }
  789.  
  790.   if($opt->{variables}) { 
  791.     $self->{_var_values} = { %{$opt->{variables}} };
  792.   }
  793.   elsif($opt->{varattr}) { 
  794.     $self->{_var_values} = {};
  795.   }
  796.  
  797. }
  798.  
  799.  
  800. ##############################################################################
  801. # Method: find_xml_file()
  802. #
  803. # Helper routine for XMLin().
  804. # Takes a filename, and a list of directories, attempts to locate the file in
  805. # the directories listed.
  806. # Returns a full pathname on success; croaks on failure.
  807. #
  808.  
  809. sub find_xml_file  {
  810.   my $self = shift;
  811.   my $file = shift;
  812.   my @search_path = @_;
  813.  
  814.  
  815.   my($filename, $filedir) =
  816.     File::Basename::fileparse($file);
  817.  
  818.   if($filename ne $file) {        # Ignore searchpath if dir component
  819.     return($file) if(-e $file);
  820.   }
  821.   else {
  822.     my($path);
  823.     foreach $path (@search_path)  {
  824.       my $fullpath = File::Spec->catfile($path, $file);
  825.       return($fullpath) if(-e $fullpath);
  826.     }
  827.   }
  828.  
  829.   # If user did not supply a search path, default to current directory
  830.  
  831.   if(!@search_path) {
  832.     return($file) if(-e $file);
  833.     croak "File does not exist: $file";
  834.   }
  835.  
  836.   croak "Could not find $file in ", join(':', @search_path);
  837. }
  838.  
  839.  
  840. ##############################################################################
  841. # Method: collapse()
  842. #
  843. # Helper routine for XMLin().  This routine really comprises the 'smarts' (or
  844. # value add) of this module.
  845. #
  846. # Takes the parse tree that XML::Parser produced from the supplied XML and
  847. # recurses through it 'collapsing' unnecessary levels of indirection (nested
  848. # arrays etc) to produce a data structure that is easier to work with.
  849. #
  850. # Elements in the original parser tree are represented as an element name
  851. # followed by an arrayref.  The first element of the array is a hashref
  852. # containing the attributes.  The rest of the array contains a list of any
  853. # nested elements as name+arrayref pairs:
  854. #
  855. #  <element name>, [ { <attribute hashref> }, <element name>, [ ... ], ... ]
  856. #
  857. # The special element name '0' (zero) flags text content.
  858. #
  859. # This routine cuts down the noise by discarding any text content consisting of
  860. # only whitespace and then moves the nested elements into the attribute hash
  861. # using the name of the nested element as the hash key and the collapsed
  862. # version of the nested element as the value.  Multiple nested elements with
  863. # the same name will initially be represented as an arrayref, but this may be
  864. # 'folded' into a hashref depending on the value of the keyattr option.
  865. #
  866.  
  867. sub collapse {
  868.   my $self = shift;
  869.  
  870.  
  871.   # Start with the hash of attributes
  872.   
  873.   my $attr  = shift;
  874.   if($self->{opt}->{noattr}) {                    # Discard if 'noattr' set
  875.     $attr = {};
  876.   }
  877.   elsif($self->{opt}->{normalisespace} == 2) {
  878.     while(my($key, $value) = each %$attr) {
  879.       $attr->{$key} = $self->normalise_space($value)
  880.     }
  881.   }
  882.  
  883.  
  884.   # Do variable substitutions
  885.  
  886.   if(my $var = $self->{_var_values}) {
  887.     while(my($key, $val) = each(%$attr)) {
  888.       $val =~ s{\$\{(\w+)\}}{ $self->get_var($1) }ge;
  889.       $attr->{$key} = $val;
  890.     }
  891.   }
  892.  
  893.  
  894.   # Roll up 'value' attributes (but only if no nested elements)
  895.  
  896.   if(!@_  and  keys %$attr == 1) {
  897.     my($k) = keys %$attr;
  898.     if($self->{opt}->{valueattrlist}  and $self->{opt}->{valueattrlist}->{$k}) {
  899.       return $attr->{$k};
  900.     }
  901.   }
  902.  
  903.  
  904.   # Add any nested elements
  905.  
  906.   my($key, $val);
  907.   while(@_) {
  908.     $key = shift;
  909.     $val = shift;
  910.  
  911.     if(ref($val)) {
  912.       $val = $self->collapse(@$val);
  913.       next if(!defined($val)  and  $self->{opt}->{suppressempty});
  914.     }
  915.     elsif($key eq '0') {
  916.       next if($val =~ m{^\s*$}s);  # Skip all whitespace content
  917.  
  918.       $val = $self->normalise_space($val)
  919.         if($self->{opt}->{normalisespace} == 2);
  920.  
  921.       # do variable substitutions
  922.  
  923.       if(my $var = $self->{_var_values}) { 
  924.         $val =~ s{\$\{(\w+)\}}{ $self->get_var($1) }ge;
  925.       }
  926.  
  927.       
  928.       # look for variable definitions
  929.  
  930.       if(my $var = $self->{opt}->{varattr}) { 
  931.         if(exists $attr->{$var}) {
  932.           $self->set_var($attr->{$var}, $val);
  933.         }
  934.       }
  935.  
  936.  
  937.       # Collapse text content in element with no attributes to a string
  938.  
  939.       if(!%$attr  and  !@_) {
  940.         return($self->{opt}->{forcecontent} ? 
  941.           { $self->{opt}->{contentkey} => $val } : $val
  942.         );
  943.       }
  944.       $key = $self->{opt}->{contentkey};
  945.     }
  946.  
  947.  
  948.     # Combine duplicate attributes into arrayref if required
  949.  
  950.     if(exists($attr->{$key})) {
  951.       if(UNIVERSAL::isa($attr->{$key}, 'ARRAY')) {
  952.         push(@{$attr->{$key}}, $val);
  953.       }
  954.       else {
  955.         $attr->{$key} = [ $attr->{$key}, $val ];
  956.       }
  957.     }
  958.     elsif(defined($val)  and  UNIVERSAL::isa($val, 'ARRAY')) {
  959.       $attr->{$key} = [ $val ];
  960.     }
  961.     else {
  962.       if( $key ne $self->{opt}->{contentkey} 
  963.           and (
  964.             ($self->{opt}->{forcearray} == 1)
  965.             or ( 
  966.               (ref($self->{opt}->{forcearray}) eq 'HASH')
  967.               and (
  968.                 $self->{opt}->{forcearray}->{$key}
  969.                 or (grep $key =~ $_, @{$self->{opt}->{forcearray}->{_regex}})
  970.               )
  971.             )
  972.           )
  973.         ) {
  974.         $attr->{$key} = [ $val ];
  975.       }
  976.       else {
  977.         $attr->{$key} = $val;
  978.       }
  979.     }
  980.  
  981.   }
  982.  
  983.  
  984.   # Turn arrayrefs into hashrefs if key fields present
  985.  
  986.   if($self->{opt}->{keyattr}) {
  987.     while(($key,$val) = each %$attr) {
  988.       if(defined($val)  and  UNIVERSAL::isa($val, 'ARRAY')) {
  989.         $attr->{$key} = $self->array_to_hash($key, $val);
  990.       }
  991.     }
  992.   }
  993.  
  994.  
  995.   # disintermediate grouped tags
  996.  
  997.   if($self->{opt}->{grouptags}) {
  998.     while(my($key, $val) = each(%$attr)) {
  999.       next unless(UNIVERSAL::isa($val, 'HASH') and (keys %$val == 1));
  1000.       next unless(exists($self->{opt}->{grouptags}->{$key}));
  1001.  
  1002.       my($child_key, $child_val) =  %$val;
  1003.  
  1004.       if($self->{opt}->{grouptags}->{$key} eq $child_key) {
  1005.         $attr->{$key}= $child_val;
  1006.       }
  1007.     }
  1008.   }
  1009.  
  1010.  
  1011.   # Fold hashes containing a single anonymous array up into just the array
  1012.  
  1013.   my $count = scalar keys %$attr;
  1014.   if($count == 1 
  1015.      and  exists $attr->{anon}  
  1016.      and  UNIVERSAL::isa($attr->{anon}, 'ARRAY')
  1017.   ) {
  1018.     return($attr->{anon});
  1019.   }
  1020.  
  1021.  
  1022.   # Do the right thing if hash is empty, otherwise just return it
  1023.  
  1024.   if(!%$attr  and  exists($self->{opt}->{suppressempty})) {
  1025.     if(defined($self->{opt}->{suppressempty})  and
  1026.        $self->{opt}->{suppressempty} eq '') {
  1027.       return('');
  1028.     }
  1029.     return(undef);
  1030.   }
  1031.  
  1032.  
  1033.   # Roll up named elements with named nested 'value' attributes
  1034.  
  1035.   if($self->{opt}->{valueattr}) {
  1036.     while(my($key, $val) = each(%$attr)) {
  1037.       next unless($self->{opt}->{valueattr}->{$key});
  1038.       next unless(UNIVERSAL::isa($val, 'HASH') and (keys %$val == 1));
  1039.       my($k) = keys %$val;
  1040.       next unless($k eq $self->{opt}->{valueattr}->{$key});
  1041.       $attr->{$key} = $val->{$k};
  1042.     }
  1043.   }
  1044.  
  1045.   return($attr)
  1046.  
  1047. }
  1048.  
  1049.  
  1050. ##############################################################################
  1051. # Method: set_var()
  1052. #
  1053. # Called when a variable definition is encountered in the XML.  (A variable
  1054. # definition looks like <element attrname="name">value</element> where attrname
  1055. # matches the varattr setting).
  1056. #
  1057.  
  1058. sub set_var {
  1059.   my($self, $name, $value) = @_;
  1060.  
  1061.   $self->{_var_values}->{$name} = $value;
  1062. }
  1063.  
  1064.  
  1065. ##############################################################################
  1066. # Method: get_var()
  1067. #
  1068. # Called during variable substitution to get the value for the named variable.
  1069. #
  1070.  
  1071. sub get_var {
  1072.   my($self, $name) = @_;
  1073.  
  1074.   my $value = $self->{_var_values}->{$name};
  1075.   return $value if(defined($value));
  1076.  
  1077.   return '${' . $name . '}';
  1078. }
  1079.  
  1080.  
  1081. ##############################################################################
  1082. # Method: normalise_space()
  1083. #
  1084. # Strips leading and trailing whitespace and collapses sequences of whitespace
  1085. # characters to a single space.
  1086. #
  1087.  
  1088. sub normalise_space {
  1089.   my($self, $text) = @_;
  1090.  
  1091.   $text =~ s/^\s+//s;
  1092.   $text =~ s/\s+$//s;
  1093.   $text =~ s/\s\s+/ /sg;
  1094.  
  1095.   return $text;
  1096. }
  1097.  
  1098.  
  1099. ##############################################################################
  1100. # Method: array_to_hash()
  1101. #
  1102. # Helper routine for collapse().
  1103. # Attempts to 'fold' an array of hashes into an hash of hashes.  Returns a
  1104. # reference to the hash on success or the original array if folding is
  1105. # not possible.  Behaviour is controlled by 'keyattr' option.
  1106. #
  1107.  
  1108. sub array_to_hash {
  1109.   my $self     = shift;
  1110.   my $name     = shift;
  1111.   my $arrayref = shift;
  1112.  
  1113.   my $hashref  = {};
  1114.  
  1115.   my($i, $key, $val, $flag);
  1116.  
  1117.  
  1118.   # Handle keyattr => { .... }
  1119.  
  1120.   if(ref($self->{opt}->{keyattr}) eq 'HASH') {
  1121.     return($arrayref) unless(exists($self->{opt}->{keyattr}->{$name}));
  1122.     ($key, $flag) = @{$self->{opt}->{keyattr}->{$name}};
  1123.     for($i = 0; $i < @$arrayref; $i++)  {
  1124.       if(UNIVERSAL::isa($arrayref->[$i], 'HASH') and
  1125.          exists($arrayref->[$i]->{$key})
  1126.       ) {
  1127.         $val = $arrayref->[$i]->{$key};
  1128.         if(ref($val)) {
  1129.           if($StrictMode) {
  1130.             croak "<$name> element has non-scalar '$key' key attribute";
  1131.           }
  1132.           if($^W) {
  1133.             carp "Warning: <$name> element has non-scalar '$key' key attribute";
  1134.           }
  1135.           return($arrayref);
  1136.         }
  1137.         $val = $self->normalise_space($val)
  1138.           if($self->{opt}->{normalisespace} == 1);
  1139.         $hashref->{$val} = { %{$arrayref->[$i]} };
  1140.         $hashref->{$val}->{"-$key"} = $hashref->{$val}->{$key} if($flag eq '-');
  1141.         delete $hashref->{$val}->{$key} unless($flag eq '+');
  1142.       }
  1143.       else {
  1144.         croak "<$name> element has no '$key' key attribute" if($StrictMode);
  1145.         carp "Warning: <$name> element has no '$key' key attribute" if($^W);
  1146.         return($arrayref);
  1147.       }
  1148.     }
  1149.   }
  1150.  
  1151.  
  1152.   # Or assume keyattr => [ .... ]
  1153.  
  1154.   else {
  1155.     ELEMENT: for($i = 0; $i < @$arrayref; $i++)  {
  1156.       return($arrayref) unless(UNIVERSAL::isa($arrayref->[$i], 'HASH'));
  1157.  
  1158.       foreach $key (@{$self->{opt}->{keyattr}}) {
  1159.         if(defined($arrayref->[$i]->{$key}))  {
  1160.           $val = $arrayref->[$i]->{$key};
  1161.           return($arrayref) if(ref($val));
  1162.           $val = $self->normalise_space($val)
  1163.             if($self->{opt}->{normalisespace} == 1);
  1164.           $hashref->{$val} = { %{$arrayref->[$i]} };
  1165.           delete $hashref->{$val}->{$key};
  1166.           next ELEMENT;
  1167.         }
  1168.       }
  1169.  
  1170.       return($arrayref);    # No keyfield matched
  1171.     }
  1172.   }
  1173.   
  1174.   # collapse any hashes which now only have a 'content' key
  1175.  
  1176.   if($self->{opt}->{collapseagain}) {
  1177.     $hashref = $self->collapse_content($hashref);
  1178.   }
  1179.  
  1180.   return($hashref);
  1181. }
  1182.  
  1183.  
  1184. ##############################################################################
  1185. # Method: collapse_content()
  1186. #
  1187. # Helper routine for array_to_hash
  1188. # Arguments expected are:
  1189. # - an XML::Simple object
  1190. # - a hasref
  1191. # the hashref is a former array, turned into a hash by array_to_hash because
  1192. # of the presence of key attributes
  1193. # at this point collapse_content avoids over-complicated structures like
  1194. # dir => { libexecdir    => { content => '$exec_prefix/libexec' },
  1195. #          localstatedir => { content => '$prefix' },
  1196. #        }
  1197. # into
  1198. # dir => { libexecdir    => '$exec_prefix/libexec',
  1199. #          localstatedir => '$prefix',
  1200. #        }
  1201.  
  1202. sub collapse_content {
  1203.   my $self       = shift;
  1204.   my $hashref    = shift; 
  1205.  
  1206.   my $contentkey = $self->{opt}->{contentkey};
  1207.  
  1208.   # first go through the values,checking that they are fit to collapse
  1209.   foreach my $val (values %$hashref) {
  1210.     return $hashref unless (     (ref($val) eq 'HASH')
  1211.                              and (keys %$val == 1)
  1212.                              and (exists $val->{$contentkey})
  1213.                            );
  1214.   }
  1215.  
  1216.   # now collapse them
  1217.   foreach my $key (keys %$hashref) {
  1218.     $hashref->{$key}=  $hashref->{$key}->{$contentkey};
  1219.   }
  1220.  
  1221.   return $hashref;
  1222. }
  1223.   
  1224.  
  1225. ##############################################################################
  1226. # Method: value_to_xml()
  1227. #
  1228. # Helper routine for XMLout() - recurses through a data structure building up
  1229. # and returning an XML representation of that structure as a string.
  1230. # Arguments expected are:
  1231. # - the data structure to be encoded (usually a reference)
  1232. # - the XML tag name to use for this item
  1233. # - a string of spaces for use as the current indent level
  1234. #
  1235.  
  1236. sub value_to_xml {
  1237.   my $self = shift;;
  1238.  
  1239.  
  1240.   # Grab the other arguments
  1241.  
  1242.   my($ref, $name, $indent) = @_;
  1243.  
  1244.   my $named = (defined($name) and $name ne '' ? 1 : 0);
  1245.  
  1246.   my $nl = "\n";
  1247.  
  1248.   if($self->{opt}->{noindent}) {
  1249.     $indent = '';
  1250.     $nl     = '';
  1251.   }
  1252.  
  1253.  
  1254.   # Convert to XML
  1255.   
  1256.   if(ref($ref)) {
  1257.     croak "circular data structures not supported"
  1258.       if(grep($_ == $ref, @{$self->{_ancestors}}));
  1259.     push @{$self->{_ancestors}}, $ref;
  1260.   }
  1261.   else {
  1262.     if($named) {
  1263.       return(join('',
  1264.               $indent, '<', $name, '>',
  1265.               ($self->{opt}->{noescape} ? $ref : $self->escape_value($ref)),
  1266.               '</', $name, ">", $nl
  1267.             ));
  1268.     }
  1269.     else {
  1270.       return("$ref$nl");
  1271.     }
  1272.   }
  1273.  
  1274.  
  1275.   # Unfold hash to array if possible
  1276.  
  1277.   if(UNIVERSAL::isa($ref, 'HASH')      # It is a hash
  1278.      and keys %$ref                    # and it's not empty
  1279.      and $self->{opt}->{keyattr}       # and folding is enabled
  1280.      and $indent                       # and its not the root element
  1281.   ) {
  1282.     $ref = $self->hash_to_array($name, $ref);
  1283.   }
  1284.  
  1285.  
  1286.   my @result = ();
  1287.   my($key, $value);
  1288.  
  1289.  
  1290.   # Handle hashrefs
  1291.  
  1292.   if(UNIVERSAL::isa($ref, 'HASH')) {
  1293.  
  1294.     # Reintermediate grouped values if applicable
  1295.  
  1296.     if($self->{opt}->{grouptags}) {
  1297.       while(my($key, $val) = each %$ref) {
  1298.         if($self->{opt}->{grouptags}->{$key}) {
  1299.           $ref->{$key} = { $self->{opt}->{grouptags}->{$key} => $val };
  1300.         }
  1301.       }
  1302.     }
  1303.  
  1304.  
  1305.     # Scan for namespace declaration attributes
  1306.  
  1307.     my $nsdecls = '';
  1308.     my $default_ns_uri;
  1309.     if($self->{nsup}) {
  1310.       $ref = { %$ref };                # Make a copy before we mess with it
  1311.       $self->{nsup}->push_context();
  1312.  
  1313.       # Look for default namespace declaration first
  1314.  
  1315.       if(exists($ref->{xmlns})) {
  1316.         $self->{nsup}->declare_prefix('', $ref->{xmlns});
  1317.         $nsdecls .= qq( xmlns="$ref->{xmlns}"); 
  1318.         delete($ref->{xmlns});
  1319.       }
  1320.       $default_ns_uri = $self->{nsup}->get_uri('');
  1321.  
  1322.  
  1323.       # Then check all the other keys
  1324.  
  1325.       foreach my $qname (keys(%$ref)) {
  1326.         my($uri, $lname) = $self->{nsup}->parse_jclark_notation($qname);
  1327.         if($uri) {
  1328.           if($uri eq $xmlns_ns) {
  1329.             $self->{nsup}->declare_prefix($lname, $ref->{$qname});
  1330.             $nsdecls .= qq( xmlns:$lname="$ref->{$qname}"); 
  1331.             delete($ref->{$qname});
  1332.           }
  1333.         }
  1334.       }
  1335.  
  1336.       # Translate any remaining Clarkian names
  1337.  
  1338.       foreach my $qname (keys(%$ref)) {
  1339.         my($uri, $lname) = $self->{nsup}->parse_jclark_notation($qname);
  1340.         if($uri) {
  1341.           if($default_ns_uri  and  $uri eq $default_ns_uri) {
  1342.             $ref->{$lname} = $ref->{$qname};
  1343.             delete($ref->{$qname});
  1344.           }
  1345.           else {
  1346.             my $prefix = $self->{nsup}->get_prefix($uri);
  1347.             unless($prefix) {
  1348.               # $self->{nsup}->declare_prefix(undef, $uri);
  1349.               # $prefix = $self->{nsup}->get_prefix($uri);
  1350.               $prefix = $self->{ns_prefix}++;
  1351.               $self->{nsup}->declare_prefix($prefix, $uri);
  1352.               $nsdecls .= qq( xmlns:$prefix="$uri"); 
  1353.             }
  1354.             $ref->{"$prefix:$lname"} = $ref->{$qname};
  1355.             delete($ref->{$qname});
  1356.           }
  1357.         }
  1358.       }
  1359.     }
  1360.  
  1361.  
  1362.     my @nested = ();
  1363.     my $text_content = undef;
  1364.     if($named) {
  1365.       push @result, $indent, '<', $name, $nsdecls;
  1366.     }
  1367.  
  1368.     if(keys %$ref) {
  1369.       my $first_arg = 1;
  1370.       foreach my $key ($self->sorted_keys($name, $ref)) {
  1371.         my $value = $ref->{$key};
  1372.         next if(substr($key, 0, 1) eq '-');
  1373.         if(!defined($value)) {
  1374.           unless(exists($self->{opt}->{suppressempty})
  1375.              and !defined($self->{opt}->{suppressempty})
  1376.           ) {
  1377.             carp 'Use of uninitialized value' if($^W);
  1378.           }
  1379.           if($key eq $self->{opt}->{contentkey}) {
  1380.             $text_content = '';
  1381.           }
  1382.           else {
  1383.             $value = {};
  1384.           }
  1385.         }
  1386.  
  1387.         if(!ref($value)  
  1388.            and $self->{opt}->{valueattr}
  1389.            and $self->{opt}->{valueattr}->{$key}
  1390.         ) {
  1391.           $value = { $self->{opt}->{valueattr}->{$key} => $value };
  1392.         }
  1393.  
  1394.         if(ref($value)  or  $self->{opt}->{noattr}) {
  1395.           push @nested,
  1396.             $self->value_to_xml($value, $key, "$indent  ");
  1397.         }
  1398.         else {
  1399.           $value = $self->escape_value($value) unless($self->{opt}->{noescape});
  1400.           if($key eq $self->{opt}->{contentkey}) {
  1401.             $text_content = $value;
  1402.           }
  1403.           else {
  1404.             push @result, "\n$indent " . ' ' x length($name)
  1405.               if($self->{opt}->{attrindent}  and  !$first_arg);
  1406.             push @result, ' ', $key, '="', $value , '"';
  1407.             $first_arg = 0;
  1408.           }
  1409.         }
  1410.       }
  1411.     }
  1412.     else {
  1413.       $text_content = '';
  1414.     }
  1415.  
  1416.     if(@nested  or  defined($text_content)) {
  1417.       if($named) {
  1418.         push @result, ">";
  1419.         if(defined($text_content)) {
  1420.           push @result, $text_content;
  1421.           $nested[0] =~ s/^\s+// if(@nested);
  1422.         }
  1423.         else {
  1424.           push @result, $nl;
  1425.         }
  1426.         if(@nested) {
  1427.           push @result, @nested, $indent;
  1428.         }
  1429.         push @result, '</', $name, ">", $nl;
  1430.       }
  1431.       else {
  1432.         push @result, @nested;             # Special case if no root elements
  1433.       }
  1434.     }
  1435.     else {
  1436.       push @result, " />", $nl;
  1437.     }
  1438.     $self->{nsup}->pop_context() if($self->{nsup});
  1439.   }
  1440.  
  1441.  
  1442.   # Handle arrayrefs
  1443.  
  1444.   elsif(UNIVERSAL::isa($ref, 'ARRAY')) {
  1445.     foreach $value (@$ref) {
  1446.       if(!ref($value)) {
  1447.         push @result,
  1448.              $indent, '<', $name, '>',
  1449.              ($self->{opt}->{noescape} ? $value : $self->escape_value($value)),
  1450.              '</', $name, ">$nl";
  1451.       }
  1452.       elsif(UNIVERSAL::isa($value, 'HASH')) {
  1453.         push @result, $self->value_to_xml($value, $name, $indent);
  1454.       }
  1455.       else {
  1456.         push @result,
  1457.                $indent, '<', $name, ">$nl",
  1458.                $self->value_to_xml($value, 'anon', "$indent  "),
  1459.                $indent, '</', $name, ">$nl";
  1460.       }
  1461.     }
  1462.   }
  1463.  
  1464.   else {
  1465.     croak "Can't encode a value of type: " . ref($ref);
  1466.   }
  1467.  
  1468.  
  1469.   pop @{$self->{_ancestors}} if(ref($ref));
  1470.  
  1471.   return(join('', @result));
  1472. }
  1473.  
  1474.  
  1475. ##############################################################################
  1476. # Method: sorted_keys()
  1477. #
  1478. # Returns the keys of the referenced hash sorted into alphabetical order, but
  1479. # with the 'key' key (as in KeyAttr) first, if there is one.
  1480. #
  1481.  
  1482. sub sorted_keys {
  1483.   my($self, $name, $ref) = @_;
  1484.  
  1485.   return keys %$ref if $self->{opt}->{nosort};
  1486.  
  1487.   my %hash = %$ref;
  1488.   my $keyattr = $self->{opt}->{keyattr};
  1489.  
  1490.   my @key;
  1491.  
  1492.   if(ref $keyattr eq 'HASH') {
  1493.     if(exists $keyattr->{$name} and exists $hash{$keyattr->{$name}->[0]}) {
  1494.       push @key, $keyattr->{$name}->[0];
  1495.       delete $hash{$keyattr->{$name}->[0]};
  1496.     }
  1497.   }
  1498.   elsif(ref $keyattr eq 'ARRAY') {
  1499.     foreach (@{$keyattr}) {
  1500.       if(exists $hash{$_}) {
  1501.         push @key, $_;
  1502.         delete $hash{$_};
  1503.         last;
  1504.       }
  1505.     }
  1506.   }
  1507.  
  1508.   return(@key, sort keys %hash);
  1509. }
  1510.  
  1511. ##############################################################################
  1512. # Method: escape_value()
  1513. #
  1514. # Helper routine for automatically escaping values for XMLout().
  1515. # Expects a scalar data value.  Returns escaped version.
  1516. #
  1517.  
  1518. sub escape_value {
  1519.   my($self, $data) = @_;
  1520.  
  1521.   return '' unless(defined($data));
  1522.  
  1523.   $data =~ s/&/&/sg;
  1524.   $data =~ s/</</sg;
  1525.   $data =~ s/>/>/sg;
  1526.   $data =~ s/"/"/sg;
  1527.  
  1528.   my $level = $self->{opt}->{numericescape} or return $data;
  1529.  
  1530.   return $self->numeric_escape($data, $level);
  1531. }
  1532.  
  1533. sub numeric_escape {
  1534.   my($self, $data, $level) = @_;
  1535.  
  1536.   use utf8; # required for 5.6
  1537.  
  1538.   if($self->{opt}->{numericescape} eq '2') {
  1539.     $data =~ s/([^\x00-\x7F])/'&#' . ord($1) . ';'/gse;
  1540.   }
  1541.   else {
  1542.     $data =~ s/([^\x00-\xFF])/'&#' . ord($1) . ';'/gse;
  1543.   }
  1544.  
  1545.   return $data;
  1546. }
  1547.  
  1548.  
  1549. ##############################################################################
  1550. # Method: hash_to_array()
  1551. #
  1552. # Helper routine for value_to_xml().
  1553. # Attempts to 'unfold' a hash of hashes into an array of hashes.  Returns a
  1554. # reference to the array on success or the original hash if unfolding is
  1555. # not possible.
  1556. #
  1557.  
  1558. sub hash_to_array {
  1559.   my $self    = shift;
  1560.   my $parent  = shift;
  1561.   my $hashref = shift;
  1562.  
  1563.   my $arrayref = [];
  1564.  
  1565.   my($key, $value);
  1566.  
  1567.   my @keys = $self->{opt}->{nosort} ? keys %$hashref : sort keys %$hashref;
  1568.   foreach $key (@keys) {
  1569.     $value = $hashref->{$key};
  1570.     return($hashref) unless(UNIVERSAL::isa($value, 'HASH'));
  1571.  
  1572.     if(ref($self->{opt}->{keyattr}) eq 'HASH') {
  1573.       return($hashref) unless(defined($self->{opt}->{keyattr}->{$parent}));
  1574.       push(@$arrayref, { $self->{opt}->{keyattr}->{$parent}->[0] => $key,
  1575.                          %$value });
  1576.     }
  1577.     else {
  1578.       push(@$arrayref, { $self->{opt}->{keyattr}->[0] => $key, %$value });
  1579.     }
  1580.   }
  1581.  
  1582.   return($arrayref);
  1583. }
  1584.  
  1585.  
  1586. ##############################################################################
  1587. # Methods required for building trees from SAX events
  1588. ##############################################################################
  1589.  
  1590. sub start_document {
  1591.   my $self = shift;
  1592.  
  1593.   $self->handle_options('in') unless($self->{opt});
  1594.  
  1595.   $self->{lists} = [];
  1596.   $self->{curlist} = $self->{tree} = [];
  1597. }
  1598.  
  1599.  
  1600. sub start_element {
  1601.   my $self    = shift;
  1602.   my $element = shift;
  1603.  
  1604.   my $name = $element->{Name};
  1605.   if($self->{opt}->{nsexpand}) {
  1606.     $name = $element->{LocalName} || '';
  1607.     if($element->{NamespaceURI}) {
  1608.       $name = '{' . $element->{NamespaceURI} . '}' . $name;
  1609.     }
  1610.   }
  1611.   my $attributes = {};
  1612.   if($element->{Attributes}) {  # Might be undef
  1613.     foreach my $attr (values %{$element->{Attributes}}) {
  1614.       if($self->{opt}->{nsexpand}) {
  1615.         my $name = $attr->{LocalName} || '';
  1616.         if($attr->{NamespaceURI}) {
  1617.           $name = '{' . $attr->{NamespaceURI} . '}' . $name
  1618.         }
  1619.         $name = 'xmlns' if($name eq $bad_def_ns_jcn);
  1620.         $attributes->{$name} = $attr->{Value};
  1621.       }
  1622.       else {
  1623.         $attributes->{$attr->{Name}} = $attr->{Value};
  1624.       }
  1625.     }
  1626.   }
  1627.   my $newlist = [ $attributes ];
  1628.   push @{ $self->{lists} }, $self->{curlist};
  1629.   push @{ $self->{curlist} }, $name => $newlist;
  1630.   $self->{curlist} = $newlist;
  1631. }
  1632.  
  1633.  
  1634. sub characters {
  1635.   my $self  = shift;
  1636.   my $chars = shift;
  1637.  
  1638.   my $text  = $chars->{Data};
  1639.   my $clist = $self->{curlist};
  1640.   my $pos = $#$clist;
  1641.   
  1642.   if ($pos > 0 and $clist->[$pos - 1] eq '0') {
  1643.     $clist->[$pos] .= $text;
  1644.   }
  1645.   else {
  1646.     push @$clist, 0 => $text;
  1647.   }
  1648. }
  1649.  
  1650.  
  1651. sub end_element {
  1652.   my $self    = shift;
  1653.  
  1654.   $self->{curlist} = pop @{ $self->{lists} };
  1655. }
  1656.  
  1657.  
  1658. sub end_document {
  1659.   my $self = shift;
  1660.  
  1661.   delete($self->{curlist});
  1662.   delete($self->{lists});
  1663.  
  1664.   my $tree = $self->{tree};
  1665.   delete($self->{tree});
  1666.  
  1667.  
  1668.   # Return tree as-is to XMLin()
  1669.  
  1670.   return($tree) if($self->{nocollapse});
  1671.  
  1672.  
  1673.   # Or collapse it before returning it to SAX parser class
  1674.   
  1675.   if($self->{opt}->{keeproot}) {
  1676.     $tree = $self->collapse({}, @$tree);
  1677.   }
  1678.   else {
  1679.     $tree = $self->collapse(@{$tree->[1]});
  1680.   }
  1681.  
  1682.   if($self->{opt}->{datahandler}) {
  1683.     return($self->{opt}->{datahandler}->($self, $tree));
  1684.   }
  1685.  
  1686.   return($tree);
  1687. }
  1688.  
  1689. *xml_in  = \&XMLin;
  1690. *xml_out = \&XMLout;
  1691.  
  1692. 1;
  1693.  
  1694. __END__
  1695.  
  1696. =head1 QUICK START
  1697.  
  1698. Say you have a script called B<foo> and a file of configuration options
  1699. called B<foo.xml> containing this:
  1700.  
  1701.   <config logdir="/var/log/foo/" debugfile="/tmp/foo.debug">
  1702.     <server name="sahara" osname="solaris" osversion="2.6">
  1703.       <address>10.0.0.101</address>
  1704.       <address>10.0.1.101</address>
  1705.     </server>
  1706.     <server name="gobi" osname="irix" osversion="6.5">
  1707.       <address>10.0.0.102</address>
  1708.     </server>
  1709.     <server name="kalahari" osname="linux" osversion="2.0.34">
  1710.       <address>10.0.0.103</address>
  1711.       <address>10.0.1.103</address>
  1712.     </server>
  1713.   </config>
  1714.  
  1715. The following lines of code in B<foo>:
  1716.  
  1717.   use XML::Simple;
  1718.  
  1719.   my $config = XMLin();
  1720.  
  1721. will 'slurp' the configuration options into the hashref $config (because no
  1722. arguments are passed to C<XMLin()> the name and location of the XML file will
  1723. be inferred from name and location of the script).  You can dump out the
  1724. contents of the hashref using Data::Dumper:
  1725.  
  1726.   use Data::Dumper;
  1727.  
  1728.   print Dumper($config);
  1729.  
  1730. which will produce something like this (formatting has been adjusted for
  1731. brevity):
  1732.  
  1733.   {
  1734.       'logdir'        => '/var/log/foo/',
  1735.       'debugfile'     => '/tmp/foo.debug',
  1736.       'server'        => {
  1737.           'sahara'        => {
  1738.               'osversion'     => '2.6',
  1739.               'osname'        => 'solaris',
  1740.               'address'       => [ '10.0.0.101', '10.0.1.101' ]
  1741.           },
  1742.           'gobi'          => {
  1743.               'osversion'     => '6.5',
  1744.               'osname'        => 'irix',
  1745.               'address'       => '10.0.0.102'
  1746.           },
  1747.           'kalahari'      => {
  1748.               'osversion'     => '2.0.34',
  1749.               'osname'        => 'linux',
  1750.               'address'       => [ '10.0.0.103', '10.0.1.103' ]
  1751.           }
  1752.       }
  1753.   }
  1754.  
  1755. Your script could then access the name of the log directory like this:
  1756.  
  1757.   print $config->{logdir};
  1758.  
  1759. similarly, the second address on the server 'kalahari' could be referenced as:
  1760.  
  1761.   print $config->{server}->{kalahari}->{address}->[1];
  1762.  
  1763. What could be simpler?  (Rhetorical).
  1764.  
  1765. For simple requirements, that's really all there is to it.  If you want to
  1766. store your XML in a different directory or file, or pass it in as a string or
  1767. even pass it in via some derivative of an IO::Handle, you'll need to check out
  1768. L<"OPTIONS">.  If you want to turn off or tweak the array folding feature (that
  1769. neat little transformation that produced $config->{server}) you'll find options
  1770. for that as well.
  1771.  
  1772. If you want to generate XML (for example to write a modified version of
  1773. $config back out as XML), check out C<XMLout()>.
  1774.  
  1775. If your needs are not so simple, this may not be the module for you.  In that
  1776. case, you might want to read L<"WHERE TO FROM HERE?">.
  1777.  
  1778. =head1 DESCRIPTION
  1779.  
  1780. The XML::Simple module provides a simple API layer on top of an underlying XML
  1781. parsing module (either XML::Parser or one of the SAX2 parser modules).  Two
  1782. functions are exported: C<XMLin()> and C<XMLout()>.  Note: you can explicity
  1783. request the lower case versions of the function names: C<xml_in()> and
  1784. C<xml_out()>.
  1785.  
  1786. The simplest approach is to call these two functions directly, but an
  1787. optional object oriented interface (see L<"OPTIONAL OO INTERFACE"> below)
  1788. allows them to be called as methods of an B<XML::Simple> object.  The object
  1789. interface can also be used at either end of a SAX pipeline.
  1790.  
  1791. =head2 XMLin()
  1792.  
  1793. Parses XML formatted data and returns a reference to a data structure which
  1794. contains the same information in a more readily accessible form.  (Skip
  1795. down to L<"EXAMPLES"> below, for more sample code).
  1796.  
  1797. C<XMLin()> accepts an optional XML specifier followed by zero or more 'name =>
  1798. value' option pairs.  The XML specifier can be one of the following:
  1799.  
  1800. =over 4
  1801.  
  1802. =item A filename
  1803.  
  1804. If the filename contains no directory components C<XMLin()> will look for the
  1805. file in each directory in the SearchPath (see L<"OPTIONS"> below) or in the
  1806. current directory if the SearchPath option is not defined.  eg:
  1807.  
  1808.   $ref = XMLin('/etc/params.xml');
  1809.  
  1810. Note, the filename '-' can be used to parse from STDIN.
  1811.  
  1812. =item undef
  1813.  
  1814. If there is no XML specifier, C<XMLin()> will check the script directory and
  1815. each of the SearchPath directories for a file with the same name as the script
  1816. but with the extension '.xml'.  Note: if you wish to specify options, you
  1817. must specify the value 'undef'.  eg:
  1818.  
  1819.   $ref = XMLin(undef, ForceArray => 1);
  1820.  
  1821. =item A string of XML
  1822.  
  1823. A string containing XML (recognised by the presence of '<' and '>' characters)
  1824. will be parsed directly.  eg:
  1825.  
  1826.   $ref = XMLin('<opt username="bob" password="flurp" />');
  1827.  
  1828. =item An IO::Handle object
  1829.  
  1830. An IO::Handle object will be read to EOF and its contents parsed. eg:
  1831.  
  1832.   $fh = new IO::File('/etc/params.xml');
  1833.   $ref = XMLin($fh);
  1834.  
  1835. =back
  1836.  
  1837. =head2 XMLout()
  1838.  
  1839. Takes a data structure (generally a hashref) and returns an XML encoding of
  1840. that structure.  If the resulting XML is parsed using C<XMLin()>, it should
  1841. return a data structure equivalent to the original (see caveats below). 
  1842.  
  1843. The C<XMLout()> function can also be used to output the XML as SAX events
  1844. see the C<Handler> option and L<"SAX SUPPORT"> for more details).
  1845.  
  1846. When translating hashes to XML, hash keys which have a leading '-' will be
  1847. silently skipped.  This is the approved method for marking elements of a
  1848. data structure which should be ignored by C<XMLout>.  (Note: If these items
  1849. were not skipped the key names would be emitted as element or attribute names
  1850. with a leading '-' which would not be valid XML).
  1851.  
  1852. =head2 Caveats
  1853.  
  1854. Some care is required in creating data structures which will be passed to
  1855. C<XMLout()>.  Hash keys from the data structure will be encoded as either XML
  1856. element names or attribute names.  Therefore, you should use hash key names 
  1857. which conform to the relatively strict XML naming rules:
  1858.  
  1859. Names in XML must begin with a letter.  The remaining characters may be
  1860. letters, digits, hyphens (-), underscores (_) or full stops (.).  It is also
  1861. allowable to include one colon (:) in an element name but this should only be
  1862. used when working with namespaces (B<XML::Simple> can only usefully work with
  1863. namespaces when teamed with a SAX Parser).
  1864.  
  1865. You can use other punctuation characters in hash values (just not in hash
  1866. keys) however B<XML::Simple> does not support dumping binary data.
  1867.  
  1868. If you break these rules, the current implementation of C<XMLout()> will 
  1869. simply emit non-compliant XML which will be rejected if you try to read it
  1870. back in.  (A later version of B<XML::Simple> might take a more proactive
  1871. approach).
  1872.  
  1873. Note also that although you can nest hashes and arrays to arbitrary levels,
  1874. circular data structures are not supported and will cause C<XMLout()> to die.
  1875.  
  1876. If you wish to 'round-trip' arbitrary data structures from Perl to XML and back 
  1877. to Perl, then you should probably disable array folding (using the KeyAttr
  1878. option) both with C<XMLout()> and with C<XMLin()>.  If you still don't get the 
  1879. expected results, you may prefer to use L<XML::Dumper> which is designed for
  1880. exactly that purpose.
  1881.  
  1882. Refer to L<"WHERE TO FROM HERE?"> if C<XMLout()> is too simple for your needs.
  1883.  
  1884.  
  1885. =head1 OPTIONS
  1886.  
  1887. B<XML::Simple> supports a number of options (in fact as each release of
  1888. B<XML::Simple> adds more options, the module's claim to the name 'Simple'
  1889. becomes increasingly tenuous).  If you find yourself repeatedly having to
  1890. specify the same options, you might like to investigate L<"OPTIONAL OO
  1891. INTERFACE"> below.
  1892.  
  1893. If you can't be bothered reading the documentation, refer to
  1894. L<"STRICT MODE"> to automatically catch common mistakes.
  1895.  
  1896. Because there are so many options, it's hard for new users to know which ones
  1897. are important, so here are the two you really need to know about:
  1898.  
  1899. =over 4
  1900.  
  1901. =item *
  1902.  
  1903. check out C<ForceArray> because you'll almost certainly want to turn it on
  1904.  
  1905. =item *
  1906.  
  1907. make sure you know what the C<KeyAttr> option does and what its default value is
  1908. because it may surprise you otherwise (note in particular that 'KeyAttr'
  1909. affects both C<XMLin> and C<XMLout>)
  1910.  
  1911. =back
  1912.  
  1913. The option name headings below have a trailing 'comment' - a hash followed by
  1914. two pieces of metadata:
  1915.  
  1916. =over 4
  1917.  
  1918. =item *
  1919.  
  1920. Options are marked with 'I<in>' if they are recognised by C<XMLin()> and
  1921. 'I<out>' if they are recognised by C<XMLout()>.
  1922.  
  1923. =item *
  1924.  
  1925. Each option is also flagged to indicate whether it is:
  1926.  
  1927.  'important'   - don't use the module until you understand this one
  1928.  'handy'       - you can skip this on the first time through
  1929.  'advanced'    - you can skip this on the second time through
  1930.  'SAX only'    - don't worry about this unless you're using SAX (or
  1931.                  alternatively if you need this, you also need SAX)
  1932.  'seldom used' - you'll probably never use this unless you were the
  1933.                  person that requested the feature
  1934.  
  1935. =back
  1936.  
  1937. The options are listed alphabetically:
  1938.  
  1939. Note: option names are no longer case sensitive so you can use the mixed case
  1940. versions shown here; all lower case as required by versions 2.03 and earlier;
  1941. or you can add underscores between the words (eg: key_attr).
  1942.  
  1943.  
  1944. =head2 AttrIndent => 1 I<# out - handy>
  1945.  
  1946. When you are using C<XMLout()>, enable this option to have attributes printed
  1947. one-per-line with sensible indentation rather than all on one line.
  1948.  
  1949. =head2 Cache => [ cache schemes ] I<# in - advanced>
  1950.  
  1951. Because loading the B<XML::Parser> module and parsing an XML file can consume a
  1952. significant number of CPU cycles, it is often desirable to cache the output of
  1953. C<XMLin()> for later reuse.
  1954.  
  1955. When parsing from a named file, B<XML::Simple> supports a number of caching
  1956. schemes.  The 'Cache' option may be used to specify one or more schemes (using
  1957. an anonymous array).  Each scheme will be tried in turn in the hope of finding
  1958. a cached pre-parsed representation of the XML file.  If no cached copy is
  1959. found, the file will be parsed and the first cache scheme in the list will be
  1960. used to save a copy of the results.  The following cache schemes have been
  1961. implemented:
  1962.  
  1963. =over 4
  1964.  
  1965. =item storable
  1966.  
  1967. Utilises B<Storable.pm> to read/write a cache file with the same name as the
  1968. XML file but with the extension .stor
  1969.  
  1970. =item memshare
  1971.  
  1972. When a file is first parsed, a copy of the resulting data structure is retained
  1973. in memory in the B<XML::Simple> module's namespace.  Subsequent calls to parse
  1974. the same file will return a reference to this structure.  This cached version
  1975. will persist only for the life of the Perl interpreter (which in the case of
  1976. mod_perl for example, may be some significant time).
  1977.  
  1978. Because each caller receives a reference to the same data structure, a change
  1979. made by one caller will be visible to all.  For this reason, the reference
  1980. returned should be treated as read-only.
  1981.  
  1982. =item memcopy
  1983.  
  1984. This scheme works identically to 'memshare' (above) except that each caller
  1985. receives a reference to a new data structure which is a copy of the cached
  1986. version.  Copying the data structure will add a little processing overhead,
  1987. therefore this scheme should only be used where the caller intends to modify
  1988. the data structure (or wishes to protect itself from others who might).  This
  1989. scheme uses B<Storable.pm> to perform the copy.
  1990.  
  1991. =back
  1992.  
  1993. Warning! The memory-based caching schemes compare the timestamp on the file to
  1994. the time when it was last parsed.  If the file is stored on an NFS filesystem
  1995. (or other network share) and the clock on the file server is not exactly
  1996. synchronised with the clock where your script is run, updates to the source XML
  1997. file may appear to be ignored.
  1998.  
  1999. =head2 ContentKey => 'keyname' I<# in+out - seldom used>
  2000.  
  2001. When text content is parsed to a hash value, this option let's you specify a
  2002. name for the hash key to override the default 'content'.  So for example:
  2003.  
  2004.   XMLin('<opt one="1">Text</opt>', ContentKey => 'text')
  2005.  
  2006. will parse to:
  2007.  
  2008.   { 'one' => 1, 'text' => 'Text' }
  2009.  
  2010. instead of:
  2011.  
  2012.   { 'one' => 1, 'content' => 'Text' }
  2013.  
  2014. C<XMLout()> will also honour the value of this option when converting a hashref
  2015. to XML.
  2016.  
  2017. You can also prefix your selected key name with a '-' character to have 
  2018. C<XMLin()> try a little harder to eliminate unnecessary 'content' keys after
  2019. array folding.  For example:
  2020.  
  2021.   XMLin(
  2022.     '<opt><item name="one">First</item><item name="two">Second</item></opt>', 
  2023.     KeyAttr => {item => 'name'}, 
  2024.     ForceArray => [ 'item' ],
  2025.     ContentKey => '-content'
  2026.   )
  2027.  
  2028. will parse to:
  2029.  
  2030.   {
  2031.     'item' => {
  2032.       'one' =>  'First'
  2033.       'two' =>  'Second'
  2034.     }
  2035.   }
  2036.  
  2037. rather than this (without the '-'):
  2038.  
  2039.   {
  2040.     'item' => {
  2041.       'one' => { 'content' => 'First' }
  2042.       'two' => { 'content' => 'Second' }
  2043.     }
  2044.   }
  2045.  
  2046. =head2 DataHandler => code_ref I<# in - SAX only>
  2047.  
  2048. When you use an B<XML::Simple> object as a SAX handler, it will return a
  2049. 'simple tree' data structure in the same format as C<XMLin()> would return.  If
  2050. this option is set (to a subroutine reference), then when the tree is built the
  2051. subroutine will be called and passed two arguments: a reference to the
  2052. B<XML::Simple> object and a reference to the data tree.  The return value from
  2053. the subroutine will be returned to the SAX driver.  (See L<"SAX SUPPORT"> for
  2054. more details).
  2055.  
  2056. =head2 ForceArray => 1 I<# in - important>
  2057.  
  2058. This option should be set to '1' to force nested elements to be represented
  2059. as arrays even when there is only one.  Eg, with ForceArray enabled, this
  2060. XML:
  2061.  
  2062.     <opt>
  2063.       <name>value</name>
  2064.     </opt>
  2065.  
  2066. would parse to this:
  2067.  
  2068.     {
  2069.       'name' => [
  2070.                   'value'
  2071.                 ]
  2072.     }
  2073.  
  2074. instead of this (the default):
  2075.  
  2076.     {
  2077.       'name' => 'value'
  2078.     }
  2079.  
  2080. This option is especially useful if the data structure is likely to be written
  2081. back out as XML and the default behaviour of rolling single nested elements up
  2082. into attributes is not desirable. 
  2083.  
  2084. If you are using the array folding feature, you should almost certainly enable
  2085. this option.  If you do not, single nested elements will not be parsed to
  2086. arrays and therefore will not be candidates for folding to a hash.  (Given that
  2087. the default value of 'KeyAttr' enables array folding, the default value of this
  2088. option should probably also have been enabled too - sorry).
  2089.  
  2090. =head2 ForceArray => [ names ] I<# in - important>
  2091.  
  2092. This alternative (and preferred) form of the 'ForceArray' option allows you to
  2093. specify a list of element names which should always be forced into an array
  2094. representation, rather than the 'all or nothing' approach above.
  2095.  
  2096. It is also possible (since version 2.05) to include compiled regular
  2097. expressions in the list - any element names which match the pattern will be
  2098. forced to arrays.  If the list contains only a single regex, then it is not
  2099. necessary to enclose it in an arrayref.  Eg:
  2100.  
  2101.   ForceArray => qr/_list$/
  2102.  
  2103. =head2 ForceContent => 1 I<# in - seldom used>
  2104.  
  2105. When C<XMLin()> parses elements which have text content as well as attributes,
  2106. the text content must be represented as a hash value rather than a simple
  2107. scalar.  This option allows you to force text content to always parse to
  2108. a hash value even when there are no attributes.  So for example:
  2109.  
  2110.   XMLin('<opt><x>text1</x><y a="2">text2</y></opt>', ForceContent => 1)
  2111.  
  2112. will parse to:
  2113.  
  2114.   {
  2115.     'x' => {           'content' => 'text1' },
  2116.     'y' => { 'a' => 2, 'content' => 'text2' }
  2117.   }
  2118.  
  2119. instead of:
  2120.  
  2121.   {
  2122.     'x' => 'text1',
  2123.     'y' => { 'a' => 2, 'content' => 'text2' }
  2124.   }
  2125.  
  2126. =head2 GroupTags => { grouping tag => grouped tag } I<# in+out - handy>
  2127.  
  2128. You can use this option to eliminate extra levels of indirection in your Perl
  2129. data structure.  For example this XML:
  2130.  
  2131.   <opt>
  2132.    <searchpath>
  2133.      <dir>/usr/bin</dir>
  2134.      <dir>/usr/local/bin</dir>
  2135.      <dir>/usr/X11/bin</dir>
  2136.    </searchpath>
  2137.  </opt>
  2138.  
  2139. Would normally be read into a structure like this:
  2140.  
  2141.   {
  2142.     searchpath => {
  2143.                     dir => [ '/usr/bin', '/usr/local/bin', '/usr/X11/bin' ]
  2144.                   }
  2145.   }
  2146.  
  2147. But when read in with the appropriate value for 'GroupTags':
  2148.  
  2149.   my $opt = XMLin($xml, GroupTags => { searchpath => 'dir' });
  2150.  
  2151. It will return this simpler structure:
  2152.  
  2153.   {
  2154.     searchpath => [ '/usr/bin', '/usr/local/bin', '/usr/X11/bin' ]
  2155.   }
  2156.  
  2157. You can specify multiple 'grouping element' to 'grouped element' mappings in
  2158. the same hashref.  If this option is combined with C<KeyAttr>, the array
  2159. folding will occur first and then the grouped element names will be eliminated.
  2160.  
  2161. C<XMLout> will also use the grouptag mappings to re-introduce the tags around
  2162. the grouped elements.  Beware though that this will occur in all places that
  2163. the 'grouping tag' name occurs - you probably don't want to use the same name
  2164. for elements as well as attributes.
  2165.  
  2166. =head2 Handler => object_ref I<# out - SAX only>
  2167.  
  2168. Use the 'Handler' option to have C<XMLout()> generate SAX events rather than 
  2169. returning a string of XML.  For more details see L<"SAX SUPPORT"> below.
  2170.  
  2171. Note: the current implementation of this option generates a string of XML
  2172. and uses a SAX parser to translate it into SAX events.  The normal encoding
  2173. rules apply here - your data must be UTF8 encoded unless you specify an 
  2174. alternative encoding via the 'XMLDecl' option; and by the time the data reaches
  2175. the handler object, it will be in UTF8 form regardless of the encoding you
  2176. supply.  A future implementation of this option may generate the events 
  2177. directly.
  2178.  
  2179. =head2 KeepRoot => 1 I<# in+out - handy>
  2180.  
  2181. In its attempt to return a data structure free of superfluous detail and
  2182. unnecessary levels of indirection, C<XMLin()> normally discards the root
  2183. element name.  Setting the 'KeepRoot' option to '1' will cause the root element
  2184. name to be retained.  So after executing this code:
  2185.  
  2186.   $config = XMLin('<config tempdir="/tmp" />', KeepRoot => 1)
  2187.  
  2188. You'll be able to reference the tempdir as
  2189. C<$config-E<gt>{config}-E<gt>{tempdir}> instead of the default
  2190. C<$config-E<gt>{tempdir}>.
  2191.  
  2192. Similarly, setting the 'KeepRoot' option to '1' will tell C<XMLout()> that the
  2193. data structure already contains a root element name and it is not necessary to
  2194. add another.
  2195.  
  2196. =head2 KeyAttr => [ list ] I<# in+out - important>
  2197.  
  2198. This option controls the 'array folding' feature which translates nested
  2199. elements from an array to a hash.  It also controls the 'unfolding' of hashes
  2200. to arrays.
  2201.  
  2202. For example, this XML:
  2203.  
  2204.     <opt>
  2205.       <user login="grep" fullname="Gary R Epstein" />
  2206.       <user login="stty" fullname="Simon T Tyson" />
  2207.     </opt>
  2208.  
  2209. would, by default, parse to this:
  2210.  
  2211.     {
  2212.       'user' => [
  2213.                   {
  2214.                     'login' => 'grep',
  2215.                     'fullname' => 'Gary R Epstein'
  2216.                   },
  2217.                   {
  2218.                     'login' => 'stty',
  2219.                     'fullname' => 'Simon T Tyson'
  2220.                   }
  2221.                 ]
  2222.     }
  2223.  
  2224. If the option 'KeyAttr => "login"' were used to specify that the 'login'
  2225. attribute is a key, the same XML would parse to:
  2226.  
  2227.     {
  2228.       'user' => {
  2229.                   'stty' => {
  2230.                               'fullname' => 'Simon T Tyson'
  2231.                             },
  2232.                   'grep' => {
  2233.                               'fullname' => 'Gary R Epstein'
  2234.                             }
  2235.                 }
  2236.     }
  2237.  
  2238. The key attribute names should be supplied in an arrayref if there is more
  2239. than one.  C<XMLin()> will attempt to match attribute names in the order
  2240. supplied.  C<XMLout()> will use the first attribute name supplied when
  2241. 'unfolding' a hash into an array.
  2242.  
  2243. Note 1: The default value for 'KeyAttr' is ['name', 'key', 'id'].  If you do
  2244. not want folding on input or unfolding on output you must setting this option
  2245. to an empty list to disable the feature.
  2246.  
  2247. Note 2: If you wish to use this option, you should also enable the
  2248. C<ForceArray> option.  Without 'ForceArray', a single nested element will be
  2249. rolled up into a scalar rather than an array and therefore will not be folded
  2250. (since only arrays get folded).
  2251.  
  2252. =head2 KeyAttr => { list } I<# in+out - important>
  2253.  
  2254. This alternative (and preferred) method of specifiying the key attributes
  2255. allows more fine grained control over which elements are folded and on which
  2256. attributes.  For example the option 'KeyAttr => { package => 'id' } will cause
  2257. any package elements to be folded on the 'id' attribute.  No other elements
  2258. which have an 'id' attribute will be folded at all. 
  2259.  
  2260. Note: C<XMLin()> will generate a warning (or a fatal error in L<"STRICT MODE">)
  2261. if this syntax is used and an element which does not have the specified key
  2262. attribute is encountered (eg: a 'package' element without an 'id' attribute, to
  2263. use the example above).  Warnings will only be generated if B<-w> is in force.
  2264.  
  2265. Two further variations are made possible by prefixing a '+' or a '-' character
  2266. to the attribute name:
  2267.  
  2268. The option 'KeyAttr => { user => "+login" }' will cause this XML:
  2269.  
  2270.     <opt>
  2271.       <user login="grep" fullname="Gary R Epstein" />
  2272.       <user login="stty" fullname="Simon T Tyson" />
  2273.     </opt>
  2274.  
  2275. to parse to this data structure:
  2276.  
  2277.     {
  2278.       'user' => {
  2279.                   'stty' => {
  2280.                               'fullname' => 'Simon T Tyson',
  2281.                               'login'    => 'stty'
  2282.                             },
  2283.                   'grep' => {
  2284.                               'fullname' => 'Gary R Epstein',
  2285.                               'login'    => 'grep'
  2286.                             }
  2287.                 }
  2288.     }
  2289.  
  2290. The '+' indicates that the value of the key attribute should be copied rather
  2291. than moved to the folded hash key.
  2292.  
  2293. A '-' prefix would produce this result:
  2294.  
  2295.     {
  2296.       'user' => {
  2297.                   'stty' => {
  2298.                               'fullname' => 'Simon T Tyson',
  2299.                               '-login'    => 'stty'
  2300.                             },
  2301.                   'grep' => {
  2302.                               'fullname' => 'Gary R Epstein',
  2303.                               '-login'    => 'grep'
  2304.                             }
  2305.                 }
  2306.     }
  2307.  
  2308. As described earlier, C<XMLout> will ignore hash keys starting with a '-'.
  2309.  
  2310. =head2 NoAttr => 1 I<# in+out - handy>
  2311.  
  2312. When used with C<XMLout()>, the generated XML will contain no attributes.
  2313. All hash key/values will be represented as nested elements instead.
  2314.  
  2315. When used with C<XMLin()>, any attributes in the XML will be ignored.
  2316.  
  2317. =head2 NoEscape => 1 I<# out - seldom used>
  2318.  
  2319. By default, C<XMLout()> will translate the characters 'E<lt>', 'E<gt>', '&' and
  2320. '"' to '<', '>', '&' and '"' respectively.  Use this option to
  2321. suppress escaping (presumably because you've already escaped the data in some
  2322. more sophisticated manner).
  2323.  
  2324. =head2 NoIndent => 1 I<# out - seldom used>
  2325.  
  2326. Set this option to 1 to disable C<XMLout()>'s default 'pretty printing' mode.
  2327. With this option enabled, the XML output will all be on one line (unless there
  2328. are newlines in the data) - this may be easier for downstream processing.
  2329.  
  2330. =head2 NoSort => 1 I<# out - seldom used>
  2331.  
  2332. Newer versions of XML::Simple sort elements and attributes alphabetically (*),
  2333. by default.  Enable this option to suppress the sorting - possibly for
  2334. backwards compatibility.
  2335.  
  2336. * Actually, sorting is alphabetical but 'key' attribute or element names (as in
  2337. 'KeyAttr') sort first.  Also, when a hash of hashes is 'unfolded', the elements
  2338. are sorted alphabetically by the value of the key field.
  2339.  
  2340. =head2 NormaliseSpace => 0 | 1 | 2 I<# in - handy>
  2341.  
  2342. This option controls how whitespace in text content is handled.  Recognised
  2343. values for the option are:
  2344.  
  2345. =over 4
  2346.  
  2347. =item *
  2348.  
  2349. 0 = (default) whitespace is passed through unaltered (except of course for the
  2350. normalisation of whitespace in attribute values which is mandated by the XML
  2351. recommendation)
  2352.  
  2353. =item *
  2354.  
  2355. 1 = whitespace is normalised in any value used as a hash key (normalising means
  2356. removing leading and trailing whitespace and collapsing sequences of whitespace
  2357. characters to a single space)
  2358.  
  2359. =item *
  2360.  
  2361. 2 = whitespace is normalised in all text content
  2362.  
  2363. =back
  2364.  
  2365. Note: you can spell this option with a 'z' if that is more natural for you.
  2366.  
  2367. =head2 NSExpand => 1 I<# in+out handy - SAX only>
  2368.  
  2369. This option controls namespace expansion - the translation of element and
  2370. attribute names of the form 'prefix:name' to '{uri}name'.  For example the
  2371. element name 'xsl:template' might be expanded to:
  2372. '{http://www.w3.org/1999/XSL/Transform}template'.
  2373.  
  2374. By default, C<XMLin()> will return element names and attribute names exactly as
  2375. they appear in the XML.  Setting this option to 1 will cause all element and
  2376. attribute names to be expanded to include their namespace prefix.
  2377.  
  2378. I<Note: You must be using a SAX parser for this option to work (ie: it does not
  2379. work with XML::Parser)>.
  2380.  
  2381. This option also controls whether C<XMLout()> performs the reverse translation
  2382. from '{uri}name' back to 'prefix:name'.  The default is no translation.  If
  2383. your data contains expanded names, you should set this option to 1 otherwise
  2384. C<XMLout> will emit XML which is not well formed.
  2385.  
  2386. I<Note: You must have the XML::NamespaceSupport module installed if you want
  2387. C<XMLout()> to translate URIs back to prefixes>.
  2388.  
  2389. =head2 NumericEscape => 0 | 1 | 2 I<# out - handy>
  2390.  
  2391. Use this option to have 'high' (non-ASCII) characters in your Perl data
  2392. structure converted to numeric entities (eg: €) in the XML output.  Three
  2393. levels are possible:
  2394.  
  2395. 0 - default: no numeric escaping (OK if you're writing out UTF8)
  2396.  
  2397. 1 - only characters above 0xFF are escaped (ie: characters in the 0x80-FF range are not escaped), possibly useful with ISO8859-1 output
  2398.  
  2399. 2 - all characters above 0x7F are escaped (good for plain ASCII output)
  2400.  
  2401. =head2 OutputFile => <file specifier> I<# out - handy>
  2402.  
  2403. The default behaviour of C<XMLout()> is to return the XML as a string.  If you
  2404. wish to write the XML to a file, simply supply the filename using the
  2405. 'OutputFile' option.  
  2406.  
  2407. This option also accepts an IO handle object - especially useful in Perl 5.8.0 
  2408. and later for writing out in an encoding other than UTF-8, eg:
  2409.  
  2410.   open my $fh, '>:encoding(iso-8859-1)', $path or die "open($path): $!";
  2411.   XMLout($ref, OutputFile => $fh);
  2412.  
  2413. =head2 ParserOpts => [ XML::Parser Options ] I<# in - don't use this>
  2414.  
  2415. I<Note: This option is now officially deprecated.  If you find it useful, email
  2416. the author with an example of what you use it for.  Do not use this option to
  2417. set the ProtocolEncoding, that's just plain wrong - fix the XML>.
  2418.  
  2419. This option allows you to pass parameters to the constructor of the underlying
  2420. XML::Parser object (which of course assumes you're not using SAX).
  2421.  
  2422. =head2 RootName => 'string' I<# out - handy>
  2423.  
  2424. By default, when C<XMLout()> generates XML, the root element will be named
  2425. 'opt'.  This option allows you to specify an alternative name.
  2426.  
  2427. Specifying either undef or the empty string for the RootName option will
  2428. produce XML with no root elements.  In most cases the resulting XML fragment
  2429. will not be 'well formed' and therefore could not be read back in by C<XMLin()>.
  2430. Nevertheless, the option has been found to be useful in certain circumstances.
  2431.  
  2432. =head2 SearchPath => [ list ] I<# in - handy>
  2433.  
  2434. If you pass C<XMLin()> a filename, but the filename include no directory
  2435. component, you can use this option to specify which directories should be
  2436. searched to locate the file.  You might use this option to search first in the
  2437. user's home directory, then in a global directory such as /etc.
  2438.  
  2439. If a filename is provided to C<XMLin()> but SearchPath is not defined, the
  2440. file is assumed to be in the current directory.
  2441.  
  2442. If the first parameter to C<XMLin()> is undefined, the default SearchPath
  2443. will contain only the directory in which the script itself is located.
  2444. Otherwise the default SearchPath will be empty.  
  2445.  
  2446. =head2 SuppressEmpty => 1 | '' | undef I<# in+out - handy>
  2447.  
  2448. This option controls what C<XMLin()> should do with empty elements (no
  2449. attributes and no content).  The default behaviour is to represent them as
  2450. empty hashes.  Setting this option to a true value (eg: 1) will cause empty
  2451. elements to be skipped altogether.  Setting the option to 'undef' or the empty
  2452. string will cause empty elements to be represented as the undefined value or
  2453. the empty string respectively.  The latter two alternatives are a little
  2454. easier to test for in your code than a hash with no keys.
  2455.  
  2456. The option also controls what C<XMLout()> does with undefined values.
  2457. Setting the option to undef causes undefined values to be output as
  2458. empty elements (rather than empty attributes), it also suppresses the
  2459. generation of warnings about undefined values.
  2460.  
  2461. =head2 ValueAttr => [ names ] I<# in - handy>
  2462.  
  2463. Use this option to deal elements which always have a single attribute and no
  2464. content.  Eg:
  2465.  
  2466.   <opt>
  2467.     <colour value="red" />
  2468.     <size   value="XXL" />
  2469.   </opt>
  2470.  
  2471. Setting C<< ValueAttr => [ 'value' ] >> will cause the above XML to parse to:
  2472.  
  2473.   {
  2474.     colour => 'red',
  2475.     size   => 'XXL'
  2476.   }
  2477.  
  2478. instead of this (the default):
  2479.  
  2480.   {
  2481.     colour => { value => 'red' },
  2482.     size   => { value => 'XXL' }
  2483.   }
  2484.  
  2485. Note: This form of the ValueAttr option is not compatible with C<XMLout()> -
  2486. since the attribute name is discarded at parse time, the original XML cannot be
  2487. reconstructed.
  2488.  
  2489. =head2 ValueAttr => { element => attribute, ... } I<# in+out - handy>
  2490.  
  2491. This (preferred) form of the ValueAttr option requires you to specify both
  2492. the element and the attribute names.  This is not only safer, it also allows
  2493. the original XML to be reconstructed by C<XMLout()>.
  2494.  
  2495. Note: You probably don't want to use this option and the NoAttr option at the
  2496. same time.
  2497.  
  2498. =head2 Variables => { name => value } I<# in - handy>
  2499.  
  2500. This option allows variables in the XML to be expanded when the file is read.
  2501. (there is no facility for putting the variable names back if you regenerate
  2502. XML using C<XMLout>).
  2503.  
  2504. A 'variable' is any text of the form C<${name}> which occurs in an attribute
  2505. value or in the text content of an element.  If 'name' matches a key in the
  2506. supplied hashref, C<${name}> will be replaced with the corresponding value from
  2507. the hashref.  If no matching key is found, the variable will not be replaced.
  2508.  
  2509. =head2 VarAttr => 'attr_name' I<# in - handy>
  2510.  
  2511. In addition to the variables defined using C<Variables>, this option allows
  2512. variables to be defined in the XML.  A variable definition consists of an
  2513. element with an attribute called 'attr_name' (the value of the C<VarAttr>
  2514. option).  The value of the attribute will be used as the variable name and the
  2515. text content of the element will be used as the value.  A variable defined in
  2516. this way will override a variable defined using the C<Variables> option.  For
  2517. example:
  2518.  
  2519.   XMLin( '<opt>
  2520.             <dir name="prefix">/usr/local/apache</dir>
  2521.             <dir name="exec_prefix">${prefix}</dir>
  2522.             <dir name="bindir">${exec_prefix}/bin</dir>
  2523.           </opt>',
  2524.          VarAttr => 'name', ContentKey => '-content'
  2525.         );
  2526.  
  2527. produces the following data structure:
  2528.  
  2529.   {
  2530.     dir => {
  2531.              prefix      => '/usr/local/apache',
  2532.              exec_prefix => '/usr/local/apache',
  2533.              bindir      => '/usr/local/apache/bin',
  2534.            }
  2535.   }
  2536.  
  2537. =head2 XMLDecl => 1  or  XMLDecl => 'string'  I<# out - handy>
  2538.  
  2539. If you want the output from C<XMLout()> to start with the optional XML
  2540. declaration, simply set the option to '1'.  The default XML declaration is:
  2541.  
  2542.         <?xml version='1.0' standalone='yes'?>
  2543.  
  2544. If you want some other string (for example to declare an encoding value), set
  2545. the value of this option to the complete string you require.
  2546.  
  2547.  
  2548. =head1 OPTIONAL OO INTERFACE
  2549.  
  2550. The procedural interface is both simple and convenient however there are a
  2551. couple of reasons why you might prefer to use the object oriented (OO)
  2552. interface:
  2553.  
  2554. =over 4
  2555.  
  2556. =item *
  2557.  
  2558. to define a set of default values which should be used on all subsequent calls
  2559. to C<XMLin()> or C<XMLout()>
  2560.  
  2561. =item *
  2562.  
  2563. to override methods in B<XML::Simple> to provide customised behaviour
  2564.  
  2565. =back
  2566.  
  2567. The default values for the options described above are unlikely to suit
  2568. everyone.  The OO interface allows you to effectively override B<XML::Simple>'s
  2569. defaults with your preferred values.  It works like this:
  2570.  
  2571. First create an XML::Simple parser object with your preferred defaults:
  2572.  
  2573.   my $xs = new XML::Simple(ForceArray => 1, KeepRoot => 1);
  2574.  
  2575. then call C<XMLin()> or C<XMLout()> as a method of that object:
  2576.  
  2577.   my $ref = $xs->XMLin($xml);
  2578.   my $xml = $xs->XMLout($ref);
  2579.  
  2580. You can also specify options when you make the method calls and these values
  2581. will be merged with the values specified when the object was created.  Values
  2582. specified in a method call take precedence.
  2583.  
  2584. Overriding methods is a more advanced topic but might be useful if for example
  2585. you wished to provide an alternative routine for escaping character data (the
  2586. escape_value method) or for building the initial parse tree (the build_tree
  2587. method).
  2588.  
  2589. Note: when called as methods, the C<XMLin()> and C<XMLout()> routines may be
  2590. called as C<xml_in()> or C<xml_out()>.  The method names are aliased so the
  2591. only difference is the aesthetics.
  2592.  
  2593. =head1 STRICT MODE
  2594.  
  2595. If you import the B<XML::Simple> routines like this:
  2596.  
  2597.   use XML::Simple qw(:strict);
  2598.  
  2599. the following common mistakes will be detected and treated as fatal errors
  2600.  
  2601. =over 4
  2602.  
  2603. =item *
  2604.  
  2605. Failing to explicitly set the C<KeyAttr> option - if you can't be bothered
  2606. reading about this option, turn it off with: KeyAttr => [ ]
  2607.  
  2608. =item *
  2609.  
  2610. Failing to explicitly set the C<ForceArray> option - if you can't be bothered
  2611. reading about this option, set it to the safest mode with: ForceArray => 1
  2612.  
  2613. =item *
  2614.  
  2615. Setting ForceArray to an array, but failing to list all the elements from the
  2616. KeyAttr hash.
  2617.  
  2618. =item *
  2619.  
  2620. Data error - KeyAttr is set to say { part => 'partnum' } but the XML contains
  2621. one or more E<lt>partE<gt> elements without a 'partnum' attribute (or nested
  2622. element).  Note: if strict mode is not set but -w is, this condition triggers a
  2623. warning.
  2624.  
  2625. =item * 
  2626.  
  2627. Data error - as above, but value of key attribute (eg: partnum) is not a 
  2628. scalar string (due to nested elements etc).  This will also trigger a warning
  2629. if strict mode is not enabled.
  2630.  
  2631. =back
  2632.  
  2633. =head1 SAX SUPPORT
  2634.  
  2635. From version 1.08_01, B<XML::Simple> includes support for SAX (the Simple API
  2636. for XML) - specifically SAX2. 
  2637.  
  2638. In a typical SAX application, an XML parser (or SAX 'driver') module generates
  2639. SAX events (start of element, character data, end of element, etc) as it parses
  2640. an XML document and a 'handler' module processes the events to extract the
  2641. required data.  This simple model allows for some interesting and powerful
  2642. possibilities:
  2643.  
  2644. =over 4
  2645.  
  2646. =item *
  2647.  
  2648. Applications written to the SAX API can extract data from huge XML documents
  2649. without the memory overheads of a DOM or tree API.
  2650.  
  2651. =item *
  2652.  
  2653. The SAX API allows for plug and play interchange of parser modules without
  2654. having to change your code to fit a new module's API.  A number of SAX parsers
  2655. are available with capabilities ranging from extreme portability to blazing
  2656. performance.
  2657.  
  2658. =item *
  2659.  
  2660. A SAX 'filter' module can implement both a handler interface for receiving
  2661. data and a generator interface for passing modified data on to a downstream
  2662. handler.  Filters can be chained together in 'pipelines'.
  2663.  
  2664. =item *
  2665.  
  2666. One filter module might split a data stream to direct data to two or more
  2667. downstream handlers.
  2668.  
  2669. =item *
  2670.  
  2671. Generating SAX events is not the exclusive preserve of XML parsing modules.
  2672. For example, a module might extract data from a relational database using DBI
  2673. and pass it on to a SAX pipeline for filtering and formatting.
  2674.  
  2675. =back
  2676.  
  2677. B<XML::Simple> can operate at either end of a SAX pipeline.  For example,
  2678. you can take a data structure in the form of a hashref and pass it into a
  2679. SAX pipeline using the 'Handler' option on C<XMLout()>:
  2680.  
  2681.   use XML::Simple;
  2682.   use Some::SAX::Filter;
  2683.   use XML::SAX::Writer;
  2684.  
  2685.   my $ref = {
  2686.                ....   # your data here
  2687.             };
  2688.  
  2689.   my $writer = XML::SAX::Writer->new();
  2690.   my $filter = Some::SAX::Filter->new(Handler => $writer);
  2691.   my $simple = XML::Simple->new(Handler => $filter);
  2692.   $simple->XMLout($ref);
  2693.  
  2694. You can also put B<XML::Simple> at the opposite end of the pipeline to take
  2695. advantage of the simple 'tree' data structure once the relevant data has been
  2696. isolated through filtering:
  2697.  
  2698.   use XML::SAX;
  2699.   use Some::SAX::Filter;
  2700.   use XML::Simple;
  2701.  
  2702.   my $simple = XML::Simple->new(ForceArray => 1, KeyAttr => ['partnum']);
  2703.   my $filter = Some::SAX::Filter->new(Handler => $simple);
  2704.   my $parser = XML::SAX::ParserFactory->parser(Handler => $filter);
  2705.  
  2706.   my $ref = $parser->parse_uri('some_huge_file.xml');
  2707.  
  2708.   print $ref->{part}->{'555-1234'};
  2709.  
  2710. You can build a filter by using an XML::Simple object as a handler and setting
  2711. its DataHandler option to point to a routine which takes the resulting tree,
  2712. modifies it and sends it off as SAX events to a downstream handler:
  2713.  
  2714.   my $writer = XML::SAX::Writer->new();
  2715.   my $filter = XML::Simple->new(
  2716.                  DataHandler => sub {
  2717.                                   my $simple = shift;
  2718.                                   my $data = shift;
  2719.  
  2720.                                   # Modify $data here
  2721.  
  2722.                                   $simple->XMLout($data, Handler => $writer);
  2723.                                 }
  2724.                );
  2725.   my $parser = XML::SAX::ParserFactory->parser(Handler => $filter);
  2726.  
  2727.   $parser->parse_uri($filename);
  2728.  
  2729. I<Note: In this last example, the 'Handler' option was specified in the call to
  2730. C<XMLout()> but it could also have been specified in the constructor>.
  2731.  
  2732. =head1 ENVIRONMENT
  2733.  
  2734. If you don't care which parser module B<XML::Simple> uses then skip this
  2735. section entirely (it looks more complicated than it really is).
  2736.  
  2737. B<XML::Simple> will default to using a B<SAX> parser if one is available or
  2738. B<XML::Parser> if SAX is not available.
  2739.  
  2740. You can dictate which parser module is used by setting either the environment
  2741. variable 'XML_SIMPLE_PREFERRED_PARSER' or the package variable
  2742. $XML::Simple::PREFERRED_PARSER to contain the module name.  The following rules
  2743. are used:
  2744.  
  2745. =over 4
  2746.  
  2747. =item *
  2748.  
  2749. The package variable takes precedence over the environment variable if both are defined.  To force B<XML::Simple> to ignore the environment settings and use
  2750. its default rules, you can set the package variable to an empty string.
  2751.  
  2752. =item *
  2753.  
  2754. If the 'preferred parser' is set to the string 'XML::Parser', then
  2755. L<XML::Parser> will be used (or C<XMLin()> will die if L<XML::Parser> is not
  2756. installed).
  2757.  
  2758. =item * 
  2759.  
  2760. If the 'preferred parser' is set to some other value, then it is assumed to be
  2761. the name of a SAX parser module and is passed to L<XML::SAX::ParserFactory.>
  2762. If L<XML::SAX> is not installed, or the requested parser module is not
  2763. installed, then C<XMLin()> will die.
  2764.  
  2765. =item *
  2766.  
  2767. If the 'preferred parser' is not defined at all (the normal default
  2768. state), an attempt will be made to load L<XML::SAX>.  If L<XML::SAX> is
  2769. installed, then a parser module will be selected according to
  2770. L<XML::SAX::ParserFactory>'s normal rules (which typically means the last SAX
  2771. parser installed).
  2772.  
  2773. =item *
  2774.  
  2775. if the 'preferred parser' is not defined and B<XML::SAX> is not
  2776. installed, then B<XML::Parser> will be used.  C<XMLin()> will die if
  2777. L<XML::Parser> is not installed.
  2778.  
  2779. =back
  2780.  
  2781. Note: The B<XML::SAX> distribution includes an XML parser written entirely in
  2782. Perl.  It is very portable but it is not very fast.  You should consider
  2783. installing L<XML::LibXML> or L<XML::SAX::Expat> if they are available for your
  2784. platform.
  2785.  
  2786. =head1 ERROR HANDLING
  2787.  
  2788. The XML standard is very clear on the issue of non-compliant documents.  An
  2789. error in parsing any single element (for example a missing end tag) must cause
  2790. the whole document to be rejected.  B<XML::Simple> will die with an appropriate
  2791. message if it encounters a parsing error.
  2792.  
  2793. If dying is not appropriate for your application, you should arrange to call
  2794. C<XMLin()> in an eval block and look for errors in $@.  eg:
  2795.  
  2796.     my $config = eval { XMLin() };
  2797.     PopUpMessage($@) if($@);
  2798.  
  2799. Note, there is a common misconception that use of B<eval> will significantly
  2800. slow down a script.  While that may be true when the code being eval'd is in a
  2801. string, it is not true of code like the sample above.
  2802.  
  2803. =head1 EXAMPLES
  2804.  
  2805. When C<XMLin()> reads the following very simple piece of XML:
  2806.  
  2807.     <opt username="testuser" password="frodo"></opt>
  2808.  
  2809. it returns the following data structure:
  2810.  
  2811.     {
  2812.       'username' => 'testuser',
  2813.       'password' => 'frodo'
  2814.     }
  2815.  
  2816. The identical result could have been produced with this alternative XML:
  2817.  
  2818.     <opt username="testuser" password="frodo" />
  2819.  
  2820. Or this (although see 'ForceArray' option for variations):
  2821.  
  2822.     <opt>
  2823.       <username>testuser</username>
  2824.       <password>frodo</password>
  2825.     </opt>
  2826.  
  2827. Repeated nested elements are represented as anonymous arrays:
  2828.  
  2829.     <opt>
  2830.       <person firstname="Joe" lastname="Smith">
  2831.         <email>joe@smith.com</email>
  2832.         <email>jsmith@yahoo.com</email>
  2833.       </person>
  2834.       <person firstname="Bob" lastname="Smith">
  2835.         <email>bob@smith.com</email>
  2836.       </person>
  2837.     </opt>
  2838.  
  2839.     {
  2840.       'person' => [
  2841.                     {
  2842.                       'email' => [
  2843.                                    'joe@smith.com',
  2844.                                    'jsmith@yahoo.com'
  2845.                                  ],
  2846.                       'firstname' => 'Joe',
  2847.                       'lastname' => 'Smith'
  2848.                     },
  2849.                     {
  2850.                       'email' => 'bob@smith.com',
  2851.                       'firstname' => 'Bob',
  2852.                       'lastname' => 'Smith'
  2853.                     }
  2854.                   ]
  2855.     }
  2856.  
  2857. Nested elements with a recognised key attribute are transformed (folded) from
  2858. an array into a hash keyed on the value of that attribute (see the C<KeyAttr>
  2859. option):
  2860.  
  2861.     <opt>
  2862.       <person key="jsmith" firstname="Joe" lastname="Smith" />
  2863.       <person key="tsmith" firstname="Tom" lastname="Smith" />
  2864.       <person key="jbloggs" firstname="Joe" lastname="Bloggs" />
  2865.     </opt>
  2866.  
  2867.     {
  2868.       'person' => {
  2869.                     'jbloggs' => {
  2870.                                    'firstname' => 'Joe',
  2871.                                    'lastname' => 'Bloggs'
  2872.                                  },
  2873.                     'tsmith' => {
  2874.                                   'firstname' => 'Tom',
  2875.                                   'lastname' => 'Smith'
  2876.                                 },
  2877.                     'jsmith' => {
  2878.                                   'firstname' => 'Joe',
  2879.                                   'lastname' => 'Smith'
  2880.                                 }
  2881.                   }
  2882.     }
  2883.  
  2884.  
  2885. The <anon> tag can be used to form anonymous arrays:
  2886.  
  2887.     <opt>
  2888.       <head><anon>Col 1</anon><anon>Col 2</anon><anon>Col 3</anon></head>
  2889.       <data><anon>R1C1</anon><anon>R1C2</anon><anon>R1C3</anon></data>
  2890.       <data><anon>R2C1</anon><anon>R2C2</anon><anon>R2C3</anon></data>
  2891.       <data><anon>R3C1</anon><anon>R3C2</anon><anon>R3C3</anon></data>
  2892.     </opt>
  2893.  
  2894.     {
  2895.       'head' => [
  2896.                   [ 'Col 1', 'Col 2', 'Col 3' ]
  2897.                 ],
  2898.       'data' => [
  2899.                   [ 'R1C1', 'R1C2', 'R1C3' ],
  2900.                   [ 'R2C1', 'R2C2', 'R2C3' ],
  2901.                   [ 'R3C1', 'R3C2', 'R3C3' ]
  2902.                 ]
  2903.     }
  2904.  
  2905. Anonymous arrays can be nested to arbirtrary levels and as a special case, if
  2906. the surrounding tags for an XML document contain only an anonymous array the
  2907. arrayref will be returned directly rather than the usual hashref:
  2908.  
  2909.     <opt>
  2910.       <anon><anon>Col 1</anon><anon>Col 2</anon></anon>
  2911.       <anon><anon>R1C1</anon><anon>R1C2</anon></anon>
  2912.       <anon><anon>R2C1</anon><anon>R2C2</anon></anon>
  2913.     </opt>
  2914.  
  2915.     [
  2916.       [ 'Col 1', 'Col 2' ],
  2917.       [ 'R1C1', 'R1C2' ],
  2918.       [ 'R2C1', 'R2C2' ]
  2919.     ]
  2920.  
  2921. Elements which only contain text content will simply be represented as a
  2922. scalar.  Where an element has both attributes and text content, the element
  2923. will be represented as a hashref with the text content in the 'content' key
  2924. (see the C<ContentKey> option):
  2925.  
  2926.   <opt>
  2927.     <one>first</one>
  2928.     <two attr="value">second</two>
  2929.   </opt>
  2930.  
  2931.   {
  2932.     'one' => 'first',
  2933.     'two' => { 'attr' => 'value', 'content' => 'second' }
  2934.   }
  2935.  
  2936. Mixed content (elements which contain both text content and nested elements)
  2937. will be not be represented in a useful way - element order and significant
  2938. whitespace will be lost.  If you need to work with mixed content, then
  2939. XML::Simple is not the right tool for your job - check out the next section.
  2940.  
  2941. =head1 WHERE TO FROM HERE?
  2942.  
  2943. B<XML::Simple> is able to present a simple API because it makes some
  2944. assumptions on your behalf.  These include:
  2945.  
  2946. =over 4
  2947.  
  2948. =item *
  2949.  
  2950. You're not interested in text content consisting only of whitespace
  2951.  
  2952. =item * 
  2953.  
  2954. You don't mind that when things get slurped into a hash the order is lost
  2955.  
  2956. =item *
  2957.  
  2958. You don't want fine-grained control of the formatting of generated XML
  2959.  
  2960. =item *
  2961.  
  2962. You would never use a hash key that was not a legal XML element name
  2963.  
  2964. =item *
  2965.  
  2966. You don't need help converting between different encodings
  2967.  
  2968. =back
  2969.  
  2970. In a serious XML project, you'll probably outgrow these assumptions fairly
  2971. quickly.  This section of the document used to offer some advice on chosing a
  2972. more powerful option.  That advice has now grown into the 'Perl-XML FAQ'
  2973. document which you can find at: L<http://perl-xml.sourceforge.net/faq/>
  2974.  
  2975. The advice in the FAQ boils down to a quick explanation of tree versus
  2976. event based parsers and then recommends:
  2977.  
  2978. For event based parsing, use SAX (do not set out to write any new code for 
  2979. XML::Parser's handler API - it is obselete).
  2980.  
  2981. For tree-based parsing, you could choose between the 'Perlish' approach of
  2982. L<XML::Twig> and more standards based DOM implementations - preferably one with
  2983. XPath support.
  2984.  
  2985.  
  2986. =head1 SEE ALSO
  2987.  
  2988. B<XML::Simple> requires either L<XML::Parser> or L<XML::SAX>.
  2989.  
  2990. To generate documents with namespaces, L<XML::NamespaceSupport> is required.
  2991.  
  2992. The optional caching functions require L<Storable>.
  2993.  
  2994. Answers to Frequently Asked Questions about XML::Simple are bundled with this
  2995. distribution as: L<XML::Simple::FAQ>
  2996.  
  2997. =head1 COPYRIGHT 
  2998.  
  2999. Copyright 1999-2004 Grant McLean E<lt>grantm@cpan.orgE<gt>
  3000.  
  3001. This library is free software; you can redistribute it and/or modify it
  3002. under the same terms as Perl itself. 
  3003.  
  3004. =cut
  3005.  
  3006.  
  3007.