home *** CD-ROM | disk | FTP | other *** search
/ Australian Personal Computer 2004 July / APC0407D2.iso / workshop / apache / files / ActivePerl-5.6.1.638-MSWin32-x86.msi / _b6adf8023f85b0a7f12e7120cda7402d < prev    next >
Encoding:
Text File  |  2004-04-13  |  83.8 KB  |  2,841 lines

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