/src/agent/lib/XML/Simple.pm

http://keywatch.googlecode.com/ · Perl · 2282 lines · 1656 code · 354 blank · 272 comment · 206 complexity · 933f433a78dcf976f4379eb94a80bd7f MD5 · raw file

Large files are truncated click here to view the full file

  1. # $Id: Simple.pm,v 1.23 2005/01/29 04:16:10 grantm Exp $
  2. package XML::Simple;
  3. =head1 NAME
  4. XML::Simple - Easy API to maintain XML (esp config files)
  5. =head1 SYNOPSIS
  6. use XML::Simple;
  7. my $ref = XMLin([<xml file or string>] [, <options>]);
  8. my $xml = XMLout($hashref [, <options>]);
  9. Or the object oriented way:
  10. require XML::Simple;
  11. my $xs = new XML::Simple(options);
  12. my $ref = $xs->XMLin([<xml file or string>] [, <options>]);
  13. my $xml = $xs->XMLout($hashref [, <options>]);
  14. (or see L<"SAX SUPPORT"> for 'the SAX way').
  15. To catch common errors:
  16. use XML::Simple qw(:strict);
  17. (see L<"STRICT MODE"> for more details).
  18. =cut
  19. # See after __END__ for more POD documentation
  20. # Load essentials here, other modules loaded on demand later
  21. use strict;
  22. use Carp;
  23. require Exporter;
  24. ##############################################################################
  25. # Define some constants
  26. #
  27. use vars qw($VERSION @ISA @EXPORT @EXPORT_OK $PREFERRED_PARSER);
  28. @ISA = qw(Exporter);
  29. @EXPORT = qw(XMLin XMLout);
  30. @EXPORT_OK = qw(xml_in xml_out);
  31. $VERSION = '2.14';
  32. $PREFERRED_PARSER = undef;
  33. my $StrictMode = 0;
  34. my %CacheScheme = (
  35. storable => [ \&StorableSave, \&StorableRestore ],
  36. memshare => [ \&MemShareSave, \&MemShareRestore ],
  37. memcopy => [ \&MemCopySave, \&MemCopyRestore ]
  38. );
  39. my @KnownOptIn = qw(keyattr keeproot forcecontent contentkey noattr
  40. searchpath forcearray cache suppressempty parseropts
  41. grouptags nsexpand datahandler varattr variables
  42. normalisespace normalizespace valueattr);
  43. my @KnownOptOut = qw(keyattr keeproot contentkey noattr
  44. rootname xmldecl outputfile noescape suppressempty
  45. grouptags nsexpand handler noindent attrindent nosort
  46. valueattr numericescape);
  47. my @DefKeyAttr = qw(name key id);
  48. my $DefRootName = qq(opt);
  49. my $DefContentKey = qq(content);
  50. my $DefXmlDecl = qq(<?xml version='1.0' standalone='yes'?>);
  51. my $xmlns_ns = 'http://www.w3.org/2000/xmlns/';
  52. my $bad_def_ns_jcn = '{' . $xmlns_ns . '}'; # LibXML::SAX workaround
  53. ##############################################################################
  54. # Globals for use by caching routines
  55. #
  56. my %MemShareCache = ();
  57. my %MemCopyCache = ();
  58. ##############################################################################
  59. # Wrapper for Exporter - handles ':strict'
  60. #
  61. sub import {
  62. # Handle the :strict tag
  63. $StrictMode = 1 if grep(/^:strict$/, @_);
  64. # Pass everything else to Exporter.pm
  65. __PACKAGE__->export_to_level(1, grep(!/^:strict$/, @_));
  66. }
  67. ##############################################################################
  68. # Constructor for optional object interface.
  69. #
  70. sub new {
  71. my $class = shift;
  72. if(@_ % 2) {
  73. croak "Default options must be name=>value pairs (odd number supplied)";
  74. }
  75. my %known_opt;
  76. @known_opt{@KnownOptIn, @KnownOptOut} = (undef) x 100;
  77. my %raw_opt = @_;
  78. my %def_opt;
  79. while(my($key, $val) = each %raw_opt) {
  80. my $lkey = lc($key);
  81. $lkey =~ s/_//g;
  82. croak "Unrecognised option: $key" unless(exists($known_opt{$lkey}));
  83. $def_opt{$lkey} = $val;
  84. }
  85. my $self = { def_opt => \%def_opt };
  86. return(bless($self, $class));
  87. }
  88. ##############################################################################
  89. # Sub/Method: XMLin()
  90. #
  91. # Exported routine for slurping XML into a hashref - see pod for info.
  92. #
  93. # May be called as object method or as a plain function.
  94. #
  95. # Expects one arg for the source XML, optionally followed by a number of
  96. # name => value option pairs.
  97. #
  98. sub XMLin {
  99. # If this is not a method call, create an object
  100. my $self;
  101. if($_[0] and UNIVERSAL::isa($_[0], 'XML::Simple')) {
  102. $self = shift;
  103. }
  104. else {
  105. $self = new XML::Simple();
  106. }
  107. my $string = shift;
  108. $self->handle_options('in', @_);
  109. # If no XML or filename supplied, look for scriptname.xml in script directory
  110. unless(defined($string)) {
  111. # Translate scriptname[.suffix] to scriptname.xml
  112. require File::Basename;
  113. my($ScriptName, $ScriptDir, $Extension) =
  114. File::Basename::fileparse($0, '\.[^\.]+');
  115. $string = $ScriptName . '.xml';
  116. # Add script directory to searchpath
  117. if($ScriptDir) {
  118. unshift(@{$self->{opt}->{searchpath}}, $ScriptDir);
  119. }
  120. }
  121. # Are we parsing from a file? If so, is there a valid cache available?
  122. my($filename, $scheme);
  123. unless($string =~ m{<.*?>}s or ref($string) or $string eq '-') {
  124. require File::Basename;
  125. require File::Spec;
  126. $filename = $self->find_xml_file($string, @{$self->{opt}->{searchpath}});
  127. if($self->{opt}->{cache}) {
  128. foreach $scheme (@{$self->{opt}->{cache}}) {
  129. croak "Unsupported caching scheme: $scheme"
  130. unless($CacheScheme{$scheme});
  131. my $opt = $CacheScheme{$scheme}->[1]->($filename);
  132. return($opt) if($opt);
  133. }
  134. }
  135. }
  136. else {
  137. delete($self->{opt}->{cache});
  138. if($string eq '-') {
  139. # Read from standard input
  140. local($/) = undef;
  141. $string = <STDIN>;
  142. }
  143. }
  144. # Parsing is required, so let's get on with it
  145. my $tree = $self->build_tree($filename, $string);
  146. # Now work some magic on the resulting parse tree
  147. my($ref);
  148. if($self->{opt}->{keeproot}) {
  149. $ref = $self->collapse({}, @$tree);
  150. }
  151. else {
  152. $ref = $self->collapse(@{$tree->[1]});
  153. }
  154. if($self->{opt}->{cache}) {
  155. $CacheScheme{$self->{opt}->{cache}->[0]}->[0]->($ref, $filename);
  156. }
  157. return($ref);
  158. }
  159. ##############################################################################
  160. # Method: build_tree()
  161. #
  162. # This routine will be called if there is no suitable pre-parsed tree in a
  163. # cache. It parses the XML and returns an XML::Parser 'Tree' style data
  164. # structure (summarised in the comments for the collapse() routine below).
  165. #
  166. # XML::Simple requires the services of another module that knows how to
  167. # parse XML. If XML::SAX is installed, the default SAX parser will be used,
  168. # otherwise XML::Parser will be used.
  169. #
  170. # This routine expects to be passed a 'string' as argument 1 or a filename as
  171. # argument 2. The 'string' might be a string of XML or it might be a
  172. # reference to an IO::Handle. (This non-intuitive mess results in part from
  173. # the way XML::Parser works but that's really no excuse).
  174. #
  175. sub build_tree {
  176. my $self = shift;
  177. my $filename = shift;
  178. my $string = shift;
  179. my $preferred_parser = $PREFERRED_PARSER;
  180. unless(defined($preferred_parser)) {
  181. $preferred_parser = $ENV{XML_SIMPLE_PREFERRED_PARSER} || '';
  182. }
  183. if($preferred_parser eq 'XML::Parser') {
  184. return($self->build_tree_xml_parser($filename, $string));
  185. }
  186. eval { require XML::SAX; }; # We didn't need it until now
  187. if($@) { # No XML::SAX - fall back to XML::Parser
  188. if($preferred_parser) { # unless a SAX parser was expressly requested
  189. croak "XMLin() could not load XML::SAX";
  190. }
  191. return($self->build_tree_xml_parser($filename, $string));
  192. }
  193. $XML::SAX::ParserPackage = $preferred_parser if($preferred_parser);
  194. my $sp = XML::SAX::ParserFactory->parser(Handler => $self);
  195. $self->{nocollapse} = 1;
  196. my($tree);
  197. if($filename) {
  198. $tree = $sp->parse_uri($filename);
  199. }
  200. else {
  201. if(ref($string)) {
  202. $tree = $sp->parse_file($string);
  203. }
  204. else {
  205. $tree = $sp->parse_string($string);
  206. }
  207. }
  208. return($tree);
  209. }
  210. ##############################################################################
  211. # Method: build_tree_xml_parser()
  212. #
  213. # This routine will be called if XML::SAX is not installed, or if XML::Parser
  214. # was specifically requested. It takes the same arguments as build_tree() and
  215. # returns the same data structure (XML::Parser 'Tree' style).
  216. #
  217. sub build_tree_xml_parser {
  218. my $self = shift;
  219. my $filename = shift;
  220. my $string = shift;
  221. eval {
  222. local($^W) = 0; # Suppress warning from Expat.pm re File::Spec::load()
  223. require XML::Parser; # We didn't need it until now
  224. };
  225. if($@) {
  226. croak "XMLin() requires either XML::SAX or XML::Parser";
  227. }
  228. if($self->{opt}->{nsexpand}) {
  229. carp "'nsexpand' option requires XML::SAX";
  230. }
  231. my $xp = new XML::Parser(Style => 'Tree', @{$self->{opt}->{parseropts}});
  232. my($tree);
  233. if($filename) {
  234. # $tree = $xp->parsefile($filename); # Changed due to prob w/mod_perl
  235. local(*XML_FILE);
  236. open(XML_FILE, '<', $filename) || croak qq($filename - $!);
  237. $tree = $xp->parse(*XML_FILE);
  238. close(XML_FILE);
  239. }
  240. else {
  241. $tree = $xp->parse($string);
  242. }
  243. return($tree);
  244. }
  245. ##############################################################################
  246. # Sub: StorableSave()
  247. #
  248. # Wrapper routine for invoking Storable::nstore() to cache a parsed data
  249. # structure.
  250. #
  251. sub StorableSave {
  252. my($data, $filename) = @_;
  253. my $cachefile = $filename;
  254. $cachefile =~ s{(\.xml)?$}{.stor};
  255. require Storable; # We didn't need it until now
  256. if ('VMS' eq $^O) {
  257. Storable::nstore($data, $cachefile);
  258. }
  259. else {
  260. # If the following line fails for you, your Storable.pm is old - upgrade
  261. Storable::lock_nstore($data, $cachefile);
  262. }
  263. }
  264. ##############################################################################
  265. # Sub: StorableRestore()
  266. #
  267. # Wrapper routine for invoking Storable::retrieve() to read a cached parsed
  268. # data structure. Only returns cached data if the cache file exists and is
  269. # newer than the source XML file.
  270. #
  271. sub StorableRestore {
  272. my($filename) = @_;
  273. my $cachefile = $filename;
  274. $cachefile =~ s{(\.xml)?$}{.stor};
  275. return unless(-r $cachefile);
  276. return unless((stat($cachefile))[9] > (stat($filename))[9]);
  277. require Storable; # We didn't need it until now
  278. if ('VMS' eq $^O) {
  279. return(Storable::retrieve($cachefile));
  280. }
  281. else {
  282. return(Storable::lock_retrieve($cachefile));
  283. }
  284. }
  285. ##############################################################################
  286. # Sub: MemShareSave()
  287. #
  288. # Takes the supplied data structure reference and stores it away in a global
  289. # hash structure.
  290. #
  291. sub MemShareSave {
  292. my($data, $filename) = @_;
  293. $MemShareCache{$filename} = [time(), $data];
  294. }
  295. ##############################################################################
  296. # Sub: MemShareRestore()
  297. #
  298. # Takes a filename and looks in a global hash for a cached parsed version.
  299. #
  300. sub MemShareRestore {
  301. my($filename) = @_;
  302. return unless($MemShareCache{$filename});
  303. return unless($MemShareCache{$filename}->[0] > (stat($filename))[9]);
  304. return($MemShareCache{$filename}->[1]);
  305. }
  306. ##############################################################################
  307. # Sub: MemCopySave()
  308. #
  309. # Takes the supplied data structure and stores a copy of it in a global hash
  310. # structure.
  311. #
  312. sub MemCopySave {
  313. my($data, $filename) = @_;
  314. require Storable; # We didn't need it until now
  315. $MemCopyCache{$filename} = [time(), Storable::dclone($data)];
  316. }
  317. ##############################################################################
  318. # Sub: MemCopyRestore()
  319. #
  320. # Takes a filename and looks in a global hash for a cached parsed version.
  321. # Returns a reference to a copy of that data structure.
  322. #
  323. sub MemCopyRestore {
  324. my($filename) = @_;
  325. return unless($MemCopyCache{$filename});
  326. return unless($MemCopyCache{$filename}->[0] > (stat($filename))[9]);
  327. return(Storable::dclone($MemCopyCache{$filename}->[1]));
  328. }
  329. ##############################################################################
  330. # Sub/Method: XMLout()
  331. #
  332. # Exported routine for 'unslurping' a data structure out to XML.
  333. #
  334. # Expects a reference to a data structure and an optional list of option
  335. # name => value pairs.
  336. #
  337. sub XMLout {
  338. # If this is not a method call, create an object
  339. my $self;
  340. if($_[0] and UNIVERSAL::isa($_[0], 'XML::Simple')) {
  341. $self = shift;
  342. }
  343. else {
  344. $self = new XML::Simple();
  345. }
  346. croak "XMLout() requires at least one argument" unless(@_);
  347. my $ref = shift;
  348. $self->handle_options('out', @_);
  349. # If namespace expansion is set, XML::NamespaceSupport is required
  350. if($self->{opt}->{nsexpand}) {
  351. require XML::NamespaceSupport;
  352. $self->{nsup} = XML::NamespaceSupport->new();
  353. $self->{ns_prefix} = 'aaa';
  354. }
  355. # Wrap top level arrayref in a hash
  356. if(UNIVERSAL::isa($ref, 'ARRAY')) {
  357. $ref = { anon => $ref };
  358. }
  359. # Extract rootname from top level hash if keeproot enabled
  360. if($self->{opt}->{keeproot}) {
  361. my(@keys) = keys(%$ref);
  362. if(@keys == 1) {
  363. $ref = $ref->{$keys[0]};
  364. $self->{opt}->{rootname} = $keys[0];
  365. }
  366. }
  367. # Ensure there are no top level attributes if we're not adding root elements
  368. elsif($self->{opt}->{rootname} eq '') {
  369. if(UNIVERSAL::isa($ref, 'HASH')) {
  370. my $refsave = $ref;
  371. $ref = {};
  372. foreach (keys(%$refsave)) {
  373. if(ref($refsave->{$_})) {
  374. $ref->{$_} = $refsave->{$_};
  375. }
  376. else {
  377. $ref->{$_} = [ $refsave->{$_} ];
  378. }
  379. }
  380. }
  381. }
  382. # Encode the hashref and write to file if necessary
  383. $self->{_ancestors} = [];
  384. my $xml = $self->value_to_xml($ref, $self->{opt}->{rootname}, '');
  385. delete $self->{_ancestors};
  386. if($self->{opt}->{xmldecl}) {
  387. $xml = $self->{opt}->{xmldecl} . "\n" . $xml;
  388. }
  389. if($self->{opt}->{outputfile}) {
  390. if(ref($self->{opt}->{outputfile})) {
  391. return($self->{opt}->{outputfile}->print($xml));
  392. }
  393. else {
  394. local(*OUT);
  395. open(OUT, '>', "$self->{opt}->{outputfile}") ||
  396. croak "open($self->{opt}->{outputfile}): $!";
  397. binmode(OUT, ':utf8') if($] >= 5.008);
  398. print OUT $xml || croak "print: $!";
  399. close(OUT);
  400. }
  401. }
  402. elsif($self->{opt}->{handler}) {
  403. require XML::SAX;
  404. my $sp = XML::SAX::ParserFactory->parser(
  405. Handler => $self->{opt}->{handler}
  406. );
  407. return($sp->parse_string($xml));
  408. }
  409. else {
  410. return($xml);
  411. }
  412. }
  413. ##############################################################################
  414. # Method: handle_options()
  415. #
  416. # Helper routine for both XMLin() and XMLout(). Both routines handle their
  417. # first argument and assume all other args are options handled by this routine.
  418. # Saves a hash of options in $self->{opt}.
  419. #
  420. # If default options were passed to the constructor, they will be retrieved
  421. # here and merged with options supplied to the method call.
  422. #
  423. # First argument should be the string 'in' or the string 'out'.
  424. #
  425. # Remaining arguments should be name=>value pairs. Sets up default values
  426. # for options not supplied. Unrecognised options are a fatal error.
  427. #
  428. sub handle_options {
  429. my $self = shift;
  430. my $dirn = shift;
  431. # Determine valid options based on context
  432. my %known_opt;
  433. if($dirn eq 'in') {
  434. @known_opt{@KnownOptIn} = @KnownOptIn;
  435. }
  436. else {
  437. @known_opt{@KnownOptOut} = @KnownOptOut;
  438. }
  439. # Store supplied options in hashref and weed out invalid ones
  440. if(@_ % 2) {
  441. croak "Options must be name=>value pairs (odd number supplied)";
  442. }
  443. my %raw_opt = @_;
  444. my $opt = {};
  445. $self->{opt} = $opt;
  446. while(my($key, $val) = each %raw_opt) {
  447. my $lkey = lc($key);
  448. $lkey =~ s/_//g;
  449. croak "Unrecognised option: $key" unless($known_opt{$lkey});
  450. $opt->{$lkey} = $val;
  451. }
  452. # Merge in options passed to constructor
  453. foreach (keys(%known_opt)) {
  454. unless(exists($opt->{$_})) {
  455. if(exists($self->{def_opt}->{$_})) {
  456. $opt->{$_} = $self->{def_opt}->{$_};
  457. }
  458. }
  459. }
  460. # Set sensible defaults if not supplied
  461. if(exists($opt->{rootname})) {
  462. unless(defined($opt->{rootname})) {
  463. $opt->{rootname} = '';
  464. }
  465. }
  466. else {
  467. $opt->{rootname} = $DefRootName;
  468. }
  469. if($opt->{xmldecl} and $opt->{xmldecl} eq '1') {
  470. $opt->{xmldecl} = $DefXmlDecl;
  471. }
  472. if(exists($opt->{contentkey})) {
  473. if($opt->{contentkey} =~ m{^-(.*)$}) {
  474. $opt->{contentkey} = $1;
  475. $opt->{collapseagain} = 1;
  476. }
  477. }
  478. else {
  479. $opt->{contentkey} = $DefContentKey;
  480. }
  481. unless(exists($opt->{normalisespace})) {
  482. $opt->{normalisespace} = $opt->{normalizespace};
  483. }
  484. $opt->{normalisespace} = 0 unless(defined($opt->{normalisespace}));
  485. # Cleanups for values assumed to be arrays later
  486. if($opt->{searchpath}) {
  487. unless(ref($opt->{searchpath})) {
  488. $opt->{searchpath} = [ $opt->{searchpath} ];
  489. }
  490. }
  491. else {
  492. $opt->{searchpath} = [ ];
  493. }
  494. if($opt->{cache} and !ref($opt->{cache})) {
  495. $opt->{cache} = [ $opt->{cache} ];
  496. }
  497. if($opt->{cache}) {
  498. $_ = lc($_) foreach (@{$opt->{cache}});
  499. }
  500. if(exists($opt->{parseropts})) {
  501. if($^W) {
  502. carp "Warning: " .
  503. "'ParserOpts' is deprecated, contact the author if you need it";
  504. }
  505. }
  506. else {
  507. $opt->{parseropts} = [ ];
  508. }
  509. # Special cleanup for {forcearray} which could be regex, arrayref or boolean
  510. # or left to default to 0
  511. if(exists($opt->{forcearray})) {
  512. if(ref($opt->{forcearray}) eq 'Regexp') {
  513. $opt->{forcearray} = [ $opt->{forcearray} ];
  514. }
  515. if(ref($opt->{forcearray}) eq 'ARRAY') {
  516. my @force_list = @{$opt->{forcearray}};
  517. if(@force_list) {
  518. $opt->{forcearray} = {};
  519. foreach my $tag (@force_list) {
  520. if(ref($tag) eq 'Regexp') {
  521. push @{$opt->{forcearray}->{_regex}}, $tag;
  522. }
  523. else {
  524. $opt->{forcearray}->{$tag} = 1;
  525. }
  526. }
  527. }
  528. else {
  529. $opt->{forcearray} = 0;
  530. }
  531. }
  532. else {
  533. $opt->{forcearray} = ( $opt->{forcearray} ? 1 : 0 );
  534. }
  535. }
  536. else {
  537. if($StrictMode and $dirn eq 'in') {
  538. croak "No value specified for 'ForceArray' option in call to XML$dirn()";
  539. }
  540. $opt->{forcearray} = 0;
  541. }
  542. # Special cleanup for {keyattr} which could be arrayref or hashref or left
  543. # to default to arrayref
  544. if(exists($opt->{keyattr})) {
  545. if(ref($opt->{keyattr})) {
  546. if(ref($opt->{keyattr}) eq 'HASH') {
  547. # Make a copy so we can mess with it
  548. $opt->{keyattr} = { %{$opt->{keyattr}} };
  549. # Convert keyattr => { elem => '+attr' }
  550. # to keyattr => { elem => [ 'attr', '+' ] }
  551. foreach my $el (keys(%{$opt->{keyattr}})) {
  552. if($opt->{keyattr}->{$el} =~ /^(\+|-)?(.*)$/) {
  553. $opt->{keyattr}->{$el} = [ $2, ($1 ? $1 : '') ];
  554. if($StrictMode and $dirn eq 'in') {
  555. next if($opt->{forcearray} == 1);
  556. next if(ref($opt->{forcearray}) eq 'HASH'
  557. and $opt->{forcearray}->{$el});
  558. croak "<$el> set in KeyAttr but not in ForceArray";
  559. }
  560. }
  561. else {
  562. delete($opt->{keyattr}->{$el}); # Never reached (famous last words?)
  563. }
  564. }
  565. }
  566. else {
  567. if(@{$opt->{keyattr}} == 0) {
  568. delete($opt->{keyattr});
  569. }
  570. }
  571. }
  572. else {
  573. $opt->{keyattr} = [ $opt->{keyattr} ];
  574. }
  575. }
  576. else {
  577. if($StrictMode) {
  578. croak "No value specified for 'KeyAttr' option in call to XML$dirn()";
  579. }
  580. $opt->{keyattr} = [ @DefKeyAttr ];
  581. }
  582. # Special cleanup for {valueattr} which could be arrayref or hashref
  583. if(exists($opt->{valueattr})) {
  584. if(ref($opt->{valueattr}) eq 'ARRAY') {
  585. $opt->{valueattrlist} = {};
  586. $opt->{valueattrlist}->{$_} = 1 foreach(@{ delete $opt->{valueattr} });
  587. }
  588. }
  589. # make sure there's nothing weird in {grouptags}
  590. if($opt->{grouptags} and !UNIVERSAL::isa($opt->{grouptags}, 'HASH')) {
  591. croak "Illegal value for 'GroupTags' option - expected a hashref";
  592. }
  593. # Check the {variables} option is valid and initialise variables hash
  594. if($opt->{variables} and !UNIVERSAL::isa($opt->{variables}, 'HASH')) {
  595. croak "Illegal value for 'Variables' option - expected a hashref";
  596. }
  597. if($opt->{variables}) {
  598. $self->{_var_values} = { %{$opt->{variables}} };
  599. }
  600. elsif($opt->{varattr}) {
  601. $self->{_var_values} = {};
  602. }
  603. }
  604. ##############################################################################
  605. # Method: find_xml_file()
  606. #
  607. # Helper routine for XMLin().
  608. # Takes a filename, and a list of directories, attempts to locate the file in
  609. # the directories listed.
  610. # Returns a full pathname on success; croaks on failure.
  611. #
  612. sub find_xml_file {
  613. my $self = shift;
  614. my $file = shift;
  615. my @search_path = @_;
  616. my($filename, $filedir) =
  617. File::Basename::fileparse($file);
  618. if($filename ne $file) { # Ignore searchpath if dir component
  619. return($file) if(-e $file);
  620. }
  621. else {
  622. my($path);
  623. foreach $path (@search_path) {
  624. my $fullpath = File::Spec->catfile($path, $file);
  625. return($fullpath) if(-e $fullpath);
  626. }
  627. }
  628. # If user did not supply a search path, default to current directory
  629. if(!@search_path) {
  630. return($file) if(-e $file);
  631. croak "File does not exist: $file";
  632. }
  633. croak "Could not find $file in ", join(':', @search_path);
  634. }
  635. ##############################################################################
  636. # Method: collapse()
  637. #
  638. # Helper routine for XMLin(). This routine really comprises the 'smarts' (or
  639. # value add) of this module.
  640. #
  641. # Takes the parse tree that XML::Parser produced from the supplied XML and
  642. # recurses through it 'collapsing' unnecessary levels of indirection (nested
  643. # arrays etc) to produce a data structure that is easier to work with.
  644. #
  645. # Elements in the original parser tree are represented as an element name
  646. # followed by an arrayref. The first element of the array is a hashref
  647. # containing the attributes. The rest of the array contains a list of any
  648. # nested elements as name+arrayref pairs:
  649. #
  650. # <element name>, [ { <attribute hashref> }, <element name>, [ ... ], ... ]
  651. #
  652. # The special element name '0' (zero) flags text content.
  653. #
  654. # This routine cuts down the noise by discarding any text content consisting of
  655. # only whitespace and then moves the nested elements into the attribute hash
  656. # using the name of the nested element as the hash key and the collapsed
  657. # version of the nested element as the value. Multiple nested elements with
  658. # the same name will initially be represented as an arrayref, but this may be
  659. # 'folded' into a hashref depending on the value of the keyattr option.
  660. #
  661. sub collapse {
  662. my $self = shift;
  663. # Start with the hash of attributes
  664. my $attr = shift;
  665. if($self->{opt}->{noattr}) { # Discard if 'noattr' set
  666. $attr = {};
  667. }
  668. elsif($self->{opt}->{normalisespace} == 2) {
  669. while(my($key, $value) = each %$attr) {
  670. $attr->{$key} = $self->normalise_space($value)
  671. }
  672. }
  673. # Do variable substitutions
  674. if(my $var = $self->{_var_values}) {
  675. while(my($key, $val) = each(%$attr)) {
  676. $val =~ s{\$\{(\w+)\}}{ $self->get_var($1) }ge;
  677. $attr->{$key} = $val;
  678. }
  679. }
  680. # Roll up 'value' attributes (but only if no nested elements)
  681. if(!@_ and keys %$attr == 1) {
  682. my($k) = keys %$attr;
  683. if($self->{opt}->{valueattrlist} and $self->{opt}->{valueattrlist}->{$k}) {
  684. return $attr->{$k};
  685. }
  686. }
  687. # Add any nested elements
  688. my($key, $val);
  689. while(@_) {
  690. $key = shift;
  691. $val = shift;
  692. if(ref($val)) {
  693. $val = $self->collapse(@$val);
  694. next if(!defined($val) and $self->{opt}->{suppressempty});
  695. }
  696. elsif($key eq '0') {
  697. next if($val =~ m{^\s*$}s); # Skip all whitespace content
  698. $val = $self->normalise_space($val)
  699. if($self->{opt}->{normalisespace} == 2);
  700. # do variable substitutions
  701. if(my $var = $self->{_var_values}) {
  702. $val =~ s{\$\{(\w+)\}}{ $self->get_var($1) }ge;
  703. }
  704. # look for variable definitions
  705. if(my $var = $self->{opt}->{varattr}) {
  706. if(exists $attr->{$var}) {
  707. $self->set_var($attr->{$var}, $val);
  708. }
  709. }
  710. # Collapse text content in element with no attributes to a string
  711. if(!%$attr and !@_) {
  712. return($self->{opt}->{forcecontent} ?
  713. { $self->{opt}->{contentkey} => $val } : $val
  714. );
  715. }
  716. $key = $self->{opt}->{contentkey};
  717. }
  718. # Combine duplicate attributes into arrayref if required
  719. if(exists($attr->{$key})) {
  720. if(UNIVERSAL::isa($attr->{$key}, 'ARRAY')) {
  721. push(@{$attr->{$key}}, $val);
  722. }
  723. else {
  724. $attr->{$key} = [ $attr->{$key}, $val ];
  725. }
  726. }
  727. elsif(defined($val) and UNIVERSAL::isa($val, 'ARRAY')) {
  728. $attr->{$key} = [ $val ];
  729. }
  730. else {
  731. if( $key ne $self->{opt}->{contentkey}
  732. and (
  733. ($self->{opt}->{forcearray} == 1)
  734. or (
  735. (ref($self->{opt}->{forcearray}) eq 'HASH')
  736. and (
  737. $self->{opt}->{forcearray}->{$key}
  738. or (grep $key =~ $_, @{$self->{opt}->{forcearray}->{_regex}})
  739. )
  740. )
  741. )
  742. ) {
  743. $attr->{$key} = [ $val ];
  744. }
  745. else {
  746. $attr->{$key} = $val;
  747. }
  748. }
  749. }
  750. # Turn arrayrefs into hashrefs if key fields present
  751. if($self->{opt}->{keyattr}) {
  752. while(($key,$val) = each %$attr) {
  753. if(defined($val) and UNIVERSAL::isa($val, 'ARRAY')) {
  754. $attr->{$key} = $self->array_to_hash($key, $val);
  755. }
  756. }
  757. }
  758. # disintermediate grouped tags
  759. if($self->{opt}->{grouptags}) {
  760. while(my($key, $val) = each(%$attr)) {
  761. next unless(UNIVERSAL::isa($val, 'HASH') and (keys %$val == 1));
  762. next unless(exists($self->{opt}->{grouptags}->{$key}));
  763. my($child_key, $child_val) = %$val;
  764. if($self->{opt}->{grouptags}->{$key} eq $child_key) {
  765. $attr->{$key}= $child_val;
  766. }
  767. }
  768. }
  769. # Fold hashes containing a single anonymous array up into just the array
  770. my $count = scalar keys %$attr;
  771. if($count == 1
  772. and exists $attr->{anon}
  773. and UNIVERSAL::isa($attr->{anon}, 'ARRAY')
  774. ) {
  775. return($attr->{anon});
  776. }
  777. # Do the right thing if hash is empty, otherwise just return it
  778. if(!%$attr and exists($self->{opt}->{suppressempty})) {
  779. if(defined($self->{opt}->{suppressempty}) and
  780. $self->{opt}->{suppressempty} eq '') {
  781. return('');
  782. }
  783. return(undef);
  784. }
  785. # Roll up named elements with named nested 'value' attributes
  786. if($self->{opt}->{valueattr}) {
  787. while(my($key, $val) = each(%$attr)) {
  788. next unless($self->{opt}->{valueattr}->{$key});
  789. next unless(UNIVERSAL::isa($val, 'HASH') and (keys %$val == 1));
  790. my($k) = keys %$val;
  791. next unless($k eq $self->{opt}->{valueattr}->{$key});
  792. $attr->{$key} = $val->{$k};
  793. }
  794. }
  795. return($attr)
  796. }
  797. ##############################################################################
  798. # Method: set_var()
  799. #
  800. # Called when a variable definition is encountered in the XML. (A variable
  801. # definition looks like <element attrname="name">value</element> where attrname
  802. # matches the varattr setting).
  803. #
  804. sub set_var {
  805. my($self, $name, $value) = @_;
  806. $self->{_var_values}->{$name} = $value;
  807. }
  808. ##############################################################################
  809. # Method: get_var()
  810. #
  811. # Called during variable substitution to get the value for the named variable.
  812. #
  813. sub get_var {
  814. my($self, $name) = @_;
  815. my $value = $self->{_var_values}->{$name};
  816. return $value if(defined($value));
  817. return '${' . $name . '}';
  818. }
  819. ##############################################################################
  820. # Method: normalise_space()
  821. #
  822. # Strips leading and trailing whitespace and collapses sequences of whitespace
  823. # characters to a single space.
  824. #
  825. sub normalise_space {
  826. my($self, $text) = @_;
  827. $text =~ s/^\s+//s;
  828. $text =~ s/\s+$//s;
  829. $text =~ s/\s\s+/ /sg;
  830. return $text;
  831. }
  832. ##############################################################################
  833. # Method: array_to_hash()
  834. #
  835. # Helper routine for collapse().
  836. # Attempts to 'fold' an array of hashes into an hash of hashes. Returns a
  837. # reference to the hash on success or the original array if folding is
  838. # not possible. Behaviour is controlled by 'keyattr' option.
  839. #
  840. sub array_to_hash {
  841. my $self = shift;
  842. my $name = shift;
  843. my $arrayref = shift;
  844. my $hashref = {};
  845. my($i, $key, $val, $flag);
  846. # Handle keyattr => { .... }
  847. if(ref($self->{opt}->{keyattr}) eq 'HASH') {
  848. return($arrayref) unless(exists($self->{opt}->{keyattr}->{$name}));
  849. ($key, $flag) = @{$self->{opt}->{keyattr}->{$name}};
  850. for($i = 0; $i < @$arrayref; $i++) {
  851. if(UNIVERSAL::isa($arrayref->[$i], 'HASH') and
  852. exists($arrayref->[$i]->{$key})
  853. ) {
  854. $val = $arrayref->[$i]->{$key};
  855. if(ref($val)) {
  856. if($StrictMode) {
  857. croak "<$name> element has non-scalar '$key' key attribute";
  858. }
  859. if($^W) {
  860. carp "Warning: <$name> element has non-scalar '$key' key attribute";
  861. }
  862. return($arrayref);
  863. }
  864. $val = $self->normalise_space($val)
  865. if($self->{opt}->{normalisespace} == 1);
  866. $hashref->{$val} = { %{$arrayref->[$i]} };
  867. $hashref->{$val}->{"-$key"} = $hashref->{$val}->{$key} if($flag eq '-');
  868. delete $hashref->{$val}->{$key} unless($flag eq '+');
  869. }
  870. else {
  871. croak "<$name> element has no '$key' key attribute" if($StrictMode);
  872. carp "Warning: <$name> element has no '$key' key attribute" if($^W);
  873. return($arrayref);
  874. }
  875. }
  876. }
  877. # Or assume keyattr => [ .... ]
  878. else {
  879. ELEMENT: for($i = 0; $i < @$arrayref; $i++) {
  880. return($arrayref) unless(UNIVERSAL::isa($arrayref->[$i], 'HASH'));
  881. foreach $key (@{$self->{opt}->{keyattr}}) {
  882. if(defined($arrayref->[$i]->{$key})) {
  883. $val = $arrayref->[$i]->{$key};
  884. return($arrayref) if(ref($val));
  885. $val = $self->normalise_space($val)
  886. if($self->{opt}->{normalisespace} == 1);
  887. $hashref->{$val} = { %{$arrayref->[$i]} };
  888. delete $hashref->{$val}->{$key};
  889. next ELEMENT;
  890. }
  891. }
  892. return($arrayref); # No keyfield matched
  893. }
  894. }
  895. # collapse any hashes which now only have a 'content' key
  896. if($self->{opt}->{collapseagain}) {
  897. $hashref = $self->collapse_content($hashref);
  898. }
  899. return($hashref);
  900. }
  901. ##############################################################################
  902. # Method: collapse_content()
  903. #
  904. # Helper routine for array_to_hash
  905. #
  906. # Arguments expected are:
  907. # - an XML::Simple object
  908. # - a hasref
  909. # the hashref is a former array, turned into a hash by array_to_hash because
  910. # of the presence of key attributes
  911. # at this point collapse_content avoids over-complicated structures like
  912. # dir => { libexecdir => { content => '$exec_prefix/libexec' },
  913. # localstatedir => { content => '$prefix' },
  914. # }
  915. # into
  916. # dir => { libexecdir => '$exec_prefix/libexec',
  917. # localstatedir => '$prefix',
  918. # }
  919. sub collapse_content {
  920. my $self = shift;
  921. my $hashref = shift;
  922. my $contentkey = $self->{opt}->{contentkey};
  923. # first go through the values,checking that they are fit to collapse
  924. foreach my $val (values %$hashref) {
  925. return $hashref unless ( (ref($val) eq 'HASH')
  926. and (keys %$val == 1)
  927. and (exists $val->{$contentkey})
  928. );
  929. }
  930. # now collapse them
  931. foreach my $key (keys %$hashref) {
  932. $hashref->{$key}= $hashref->{$key}->{$contentkey};
  933. }
  934. return $hashref;
  935. }
  936. ##############################################################################
  937. # Method: value_to_xml()
  938. #
  939. # Helper routine for XMLout() - recurses through a data structure building up
  940. # and returning an XML representation of that structure as a string.
  941. #
  942. # Arguments expected are:
  943. # - the data structure to be encoded (usually a reference)
  944. # - the XML tag name to use for this item
  945. # - a string of spaces for use as the current indent level
  946. #
  947. sub value_to_xml {
  948. my $self = shift;;
  949. # Grab the other arguments
  950. my($ref, $name, $indent) = @_;
  951. my $named = (defined($name) and $name ne '' ? 1 : 0);
  952. my $nl = "\n";
  953. my $is_root = $indent eq '' ? 1 : 0; # Warning, dirty hack!
  954. if($self->{opt}->{noindent}) {
  955. $indent = '';
  956. $nl = '';
  957. }
  958. # Convert to XML
  959. if(ref($ref)) {
  960. croak "circular data structures not supported"
  961. if(grep($_ == $ref, @{$self->{_ancestors}}));
  962. push @{$self->{_ancestors}}, $ref;
  963. }
  964. else {
  965. if($named) {
  966. return(join('',
  967. $indent, '<', $name, '>',
  968. ($self->{opt}->{noescape} ? $ref : $self->escape_value($ref)),
  969. '</', $name, ">", $nl
  970. ));
  971. }
  972. else {
  973. return("$ref$nl");
  974. }
  975. }
  976. # Unfold hash to array if possible
  977. if(UNIVERSAL::isa($ref, 'HASH') # It is a hash
  978. and keys %$ref # and it's not empty
  979. and $self->{opt}->{keyattr} # and folding is enabled
  980. and !$is_root # and its not the root element
  981. ) {
  982. $ref = $self->hash_to_array($name, $ref);
  983. }
  984. my @result = ();
  985. my($key, $value);
  986. # Handle hashrefs
  987. if(UNIVERSAL::isa($ref, 'HASH')) {
  988. # Reintermediate grouped values if applicable
  989. if($self->{opt}->{grouptags}) {
  990. $ref = $self->copy_hash($ref);
  991. while(my($key, $val) = each %$ref) {
  992. if($self->{opt}->{grouptags}->{$key}) {
  993. $ref->{$key} = { $self->{opt}->{grouptags}->{$key} => $val };
  994. }
  995. }
  996. }
  997. # Scan for namespace declaration attributes
  998. my $nsdecls = '';
  999. my $default_ns_uri;
  1000. if($self->{nsup}) {
  1001. $ref = $self->copy_hash($ref);
  1002. $self->{nsup}->push_context();
  1003. # Look for default namespace declaration first
  1004. if(exists($ref->{xmlns})) {
  1005. $self->{nsup}->declare_prefix('', $ref->{xmlns});
  1006. $nsdecls .= qq( xmlns="$ref->{xmlns}");
  1007. delete($ref->{xmlns});
  1008. }
  1009. $default_ns_uri = $self->{nsup}->get_uri('');
  1010. # Then check all the other keys
  1011. foreach my $qname (keys(%$ref)) {
  1012. my($uri, $lname) = $self->{nsup}->parse_jclark_notation($qname);
  1013. if($uri) {
  1014. if($uri eq $xmlns_ns) {
  1015. $self->{nsup}->declare_prefix($lname, $ref->{$qname});
  1016. $nsdecls .= qq( xmlns:$lname="$ref->{$qname}");
  1017. delete($ref->{$qname});
  1018. }
  1019. }
  1020. }
  1021. # Translate any remaining Clarkian names
  1022. foreach my $qname (keys(%$ref)) {
  1023. my($uri, $lname) = $self->{nsup}->parse_jclark_notation($qname);
  1024. if($uri) {
  1025. if($default_ns_uri and $uri eq $default_ns_uri) {
  1026. $ref->{$lname} = $ref->{$qname};
  1027. delete($ref->{$qname});
  1028. }
  1029. else {
  1030. my $prefix = $self->{nsup}->get_prefix($uri);
  1031. unless($prefix) {
  1032. # $self->{nsup}->declare_prefix(undef, $uri);
  1033. # $prefix = $self->{nsup}->get_prefix($uri);
  1034. $prefix = $self->{ns_prefix}++;
  1035. $self->{nsup}->declare_prefix($prefix, $uri);
  1036. $nsdecls .= qq( xmlns:$prefix="$uri");
  1037. }
  1038. $ref->{"$prefix:$lname"} = $ref->{$qname};
  1039. delete($ref->{$qname});
  1040. }
  1041. }
  1042. }
  1043. }
  1044. my @nested = ();
  1045. my $text_content = undef;
  1046. if($named) {
  1047. push @result, $indent, '<', $name, $nsdecls;
  1048. }
  1049. if(keys %$ref) {
  1050. my $first_arg = 1;
  1051. foreach my $key ($self->sorted_keys($name, $ref)) {
  1052. my $value = $ref->{$key};
  1053. next if(substr($key, 0, 1) eq '-');
  1054. if(!defined($value)) {
  1055. next if $self->{opt}->{suppressempty};
  1056. unless(exists($self->{opt}->{suppressempty})
  1057. and !defined($self->{opt}->{suppressempty})
  1058. ) {
  1059. carp 'Use of uninitialized value' if($^W);
  1060. }
  1061. if($key eq $self->{opt}->{contentkey}) {
  1062. $text_content = '';
  1063. }
  1064. else {
  1065. $value = exists($self->{opt}->{suppressempty}) ? {} : '';
  1066. }
  1067. }
  1068. if(!ref($value)
  1069. and $self->{opt}->{valueattr}
  1070. and $self->{opt}->{valueattr}->{$key}
  1071. ) {
  1072. $value = { $self->{opt}->{valueattr}->{$key} => $value };
  1073. }
  1074. if(ref($value) or $self->{opt}->{noattr}) {
  1075. push @nested,
  1076. $self->value_to_xml($value, $key, "$indent ");
  1077. }
  1078. else {
  1079. $value = $self->escape_value($value) unless($self->{opt}->{noescape});
  1080. if($key eq $self->{opt}->{contentkey}) {
  1081. $text_content = $value;
  1082. }
  1083. else {
  1084. push @result, "\n$indent " . ' ' x length($name)
  1085. if($self->{opt}->{attrindent} and !$first_arg);
  1086. push @result, ' ', $key, '="', $value , '"';
  1087. $first_arg = 0;
  1088. }
  1089. }
  1090. }
  1091. }
  1092. else {
  1093. $text_content = '';
  1094. }
  1095. if(@nested or defined($text_content)) {
  1096. if($named) {
  1097. push @result, ">";
  1098. if(defined($text_content)) {
  1099. push @result, $text_content;
  1100. $nested[0] =~ s/^\s+// if(@nested);
  1101. }
  1102. else {
  1103. push @result, $nl;
  1104. }
  1105. if(@nested) {
  1106. push @result, @nested, $indent;
  1107. }
  1108. push @result, '</', $name, ">", $nl;
  1109. }
  1110. else {
  1111. push @result, @nested; # Special case if no root elements
  1112. }
  1113. }
  1114. else {
  1115. push @result, " />", $nl;
  1116. }
  1117. $self->{nsup}->pop_context() if($self->{nsup});
  1118. }
  1119. # Handle arrayrefs
  1120. elsif(UNIVERSAL::isa($ref, 'ARRAY')) {
  1121. foreach $value (@$ref) {
  1122. if(!ref($value)) {
  1123. push @result,
  1124. $indent, '<', $name, '>',
  1125. ($self->{opt}->{noescape} ? $value : $self->escape_value($value)),
  1126. '</', $name, ">$nl";
  1127. }
  1128. elsif(UNIVERSAL::isa($value, 'HASH')) {
  1129. push @result, $self->value_to_xml($value, $name, $indent);
  1130. }
  1131. else {
  1132. push @result,
  1133. $indent, '<', $name, ">$nl",
  1134. $self->value_to_xml($value, 'anon', "$indent "),
  1135. $indent, '</', $name, ">$nl";
  1136. }
  1137. }
  1138. }
  1139. else {
  1140. croak "Can't encode a value of type: " . ref($ref);
  1141. }
  1142. pop @{$self->{_ancestors}} if(ref($ref));
  1143. return(join('', @result));
  1144. }
  1145. ##############################################################################
  1146. # Method: sorted_keys()
  1147. #
  1148. # Returns the keys of the referenced hash sorted into alphabetical order, but
  1149. # with the 'key' key (as in KeyAttr) first, if there is one.
  1150. #
  1151. sub sorted_keys {
  1152. my($self, $name, $ref) = @_;
  1153. return keys %$ref if $self->{opt}->{nosort};
  1154. my %hash = %$ref;
  1155. my $keyattr = $self->{opt}->{keyattr};
  1156. my @key;
  1157. if(ref $keyattr eq 'HASH') {
  1158. if(exists $keyattr->{$name} and exists $hash{$keyattr->{$name}->[0]}) {
  1159. push @key, $keyattr->{$name}->[0];
  1160. delete $hash{$keyattr->{$name}->[0]};
  1161. }
  1162. }
  1163. elsif(ref $keyattr eq 'ARRAY') {
  1164. foreach (@{$keyattr}) {
  1165. if(exists $hash{$_}) {
  1166. push @key, $_;
  1167. delete $hash{$_};
  1168. last;
  1169. }
  1170. }
  1171. }
  1172. return(@key, sort keys %hash);
  1173. }
  1174. ##############################################################################
  1175. # Method: escape_value()
  1176. #
  1177. # Helper routine for automatically escaping values for XMLout().
  1178. # Expects a scalar data value. Returns escaped version.
  1179. #
  1180. sub escape_value {
  1181. my($self, $data) = @_;
  1182. return '' unless(defined($data));
  1183. $data =~ s/&/&amp;/sg;
  1184. $data =~ s/</&lt;/sg;
  1185. $data =~ s/>/&gt;/sg;
  1186. $data =~ s/"/&quot;/sg;
  1187. my $level = $self->{opt}->{numericescape} or return $data;
  1188. return $self->numeric_escape($data, $level);
  1189. }
  1190. sub numeric_escape {
  1191. my($self, $data, $level) = @_;
  1192. use utf8; # required for 5.6
  1193. if($self->{opt}->{numericescape} eq '2') {
  1194. $data =~ s/([^\x00-\x7F])/'&#' . ord($1) . ';'/gse;
  1195. }
  1196. else {
  1197. $data =~ s/([^\x00-\xFF])/'&#' . ord($1) . ';'/gse;
  1198. }
  1199. return $data;
  1200. }
  1201. ##############################################################################
  1202. # Method: hash_to_array()
  1203. #
  1204. # Helper routine for value_to_xml().
  1205. # Attempts to 'unfold' a hash of hashes into an array of hashes. Returns a
  1206. # reference to the array on success or the original hash if unfolding is
  1207. # not possible.
  1208. #
  1209. sub hash_to_array {
  1210. my $self = shift;
  1211. my $parent = shift;
  1212. my $hashref = shift;
  1213. my $arrayref = [];
  1214. my($key, $value);
  1215. my @keys = $self->{opt}->{nosort} ? keys %$hashref : sort keys %$hashref;
  1216. foreach $key (@keys) {
  1217. $value = $hashref->{$key};
  1218. return($hashref) unless(UNIVERSAL::isa($value, 'HASH'));
  1219. if(ref($self->{opt}->{keyattr}) eq 'HASH') {
  1220. return($hashref) unless(defined($self->{opt}->{keyattr}->{$parent}));
  1221. push @$arrayref, $self->copy_hash(
  1222. $value, $self->{opt}->{keyattr}->{$parent}->[0] => $key
  1223. );
  1224. }
  1225. else {
  1226. push(@$arrayref, { $self->{opt}->{keyattr}->[0] => $key, %$value });
  1227. }
  1228. }
  1229. return($arrayref);
  1230. }
  1231. ##############################################################################
  1232. # Method: copy_hash()
  1233. #
  1234. # Helper routine for hash_to_array(). When unfolding a hash of hashes into
  1235. # an array of hashes, we need to copy the key from the outer hash into the
  1236. # inner hash. This routine makes a copy of the original hash so we don't
  1237. # destroy the original data structure. You might wish to override this
  1238. # method if you're using tied hashes and don't want them to get untied.
  1239. #
  1240. sub copy_hash {
  1241. my($self, $orig, @extra) = @_;
  1242. return { @extra, %$orig };
  1243. }
  1244. ##############################################################################
  1245. # Methods required for building trees from SAX events
  1246. ##############################################################################
  1247. sub start_document {
  1248. my $self = shift;
  1249. $self->handle_options('in') unless($self->{opt});
  1250. $self->{lists} = [];
  1251. $self->{curlist} = $self->{tree} = [];
  1252. }
  1253. sub start_element {
  1254. my $self = shift;
  1255. my $element = shift;
  1256. my $name = $element->{Name};
  1257. if($self->{opt}->{nsexpand}) {
  1258. $name = $element->{LocalName} || '';
  1259. if($element->{NamespaceURI}) {
  1260. $name = '{' . $element->{NamespaceURI} . '}' . $name;
  1261. }
  1262. }
  1263. my $attributes = {};
  1264. if($element->{Attributes}) { # Might be undef
  1265. foreach my $attr (values %{$element->{Attributes}}) {
  1266. if($self->{opt}->{nsexpand}) {
  1267. my $name = $attr->{LocalName} || '';
  1268. if($attr->{NamespaceURI}) {
  1269. $name = '{' . $attr->{NamespaceURI} . '}' . $name
  1270. }
  1271. $name = 'xmlns' if($name eq $bad_def_ns_jcn);
  1272. $attributes->{$name} = $attr->{Value};
  1273. }
  1274. else {
  1275. $attributes->{$attr->{Name}} = $attr->{Value};
  1276. }
  1277. }
  1278. }
  1279. my $newlist = [ $attributes ];
  1280. push @{ $self->{lists} }, $self->{curlist};
  1281. push @{ $self->{curlist} }, $name => $newlist;
  1282. $self->{curlist} = $newlist;
  1283. }
  1284. sub characters {
  1285. my $self = shift;
  1286. my $chars = shift;
  1287. my $text = $chars->{Data};
  1288. my $clist = $self->{curlist};
  1289. my $pos = $#$clist;
  1290. if ($pos > 0 and $clist->[$pos - 1] eq '0') {
  1291. $clist->[$pos] .= $text;
  1292. }
  1293. else {
  1294. push @$clist, 0 => $text;
  1295. }
  1296. }
  1297. sub end_element {
  1298. my $self = shift;
  1299. $self->{curlist} = pop @{ $self->{lists} };
  1300. }
  1301. sub end_document {
  1302. my $self = shift;
  1303. delete($self->{curlist});
  1304. delete($self->{lists});
  1305. my $tree = $self->{tree};
  1306. delete($self->{tree});
  1307. # Return tree as-is to XMLin()
  1308. return($tree) if($self->{nocollapse});
  1309. # Or collapse it before returning it to SAX parser class
  1310. if($self->{opt}->{keeproot}) {
  1311. $tree = $self->collapse({}, @$tree);
  1312. }
  1313. else {
  1314. $tree = $self->collapse(@{$tree->[1]});
  1315. }
  1316. if($self->{opt}->{datahandler}) {
  1317. return($self->{opt}->{datahandler}->($self, $tree));
  1318. }
  1319. return($tree);
  1320. }
  1321. *xml_in = \&XMLin;
  1322. *xml_out = \&XMLout;
  1323. 1;
  1324. __END__
  1325. =head1 QUICK START
  1326. Say you have a script called B<foo> and a file of configuration options
  1327. called B<foo.xml> containing this:
  1328. <config logdir="/var/log/foo/" debugfile="/tmp/foo.debug">
  1329. <server name="sahara" osname="solaris" osversion="2.6">
  1330. <address>10.0.0.101</address>
  1331. <address>10.0.1.101</address>
  1332. </server>
  1333. <server name="gobi" osname="irix" osversion="6.5">
  1334. <address>10.0.0.102</address>
  1335. </server>
  1336. <server name="kalahari" osname="linux" osversion="2.0.34">
  1337. <address>10.0.0.103</address>
  1338. <address>10.0.1.103</address>
  1339. </server>
  1340. </config>
  1341. The following lines of code in B<foo>:
  1342. use XML::Simple;
  1343. my $config = XMLin();
  1344. will 'slurp' the configuration options into the hashref $config (because no
  1345. arguments are passed to C<XMLin()> the name and location of the XML file will
  1346. be inferred from name and location of the script). You can dump out the
  1347. contents of the hashref using Data::Dumper:
  1348. use Data::Dumper;
  1349. print Dumper($config);
  1350. which will produce something like this (formatting has been adjusted for
  1351. brevity):
  1352. {
  1353. 'logdir' => '/var/log/foo/',
  1354. 'debugfile' => '/tmp/foo.debug',
  1355. 'server' => {
  1356. 'sahara' => {
  1357. 'osversion' => '2.6',
  1358. 'osname' => 'solaris',
  1359. 'address' => [ '10.0.0.101', '10.0.1.101' ]
  1360. },
  1361. 'gobi' => {
  1362. 'osversion' => '6.5',
  1363. 'osname' => 'irix',
  1364. 'address' => '10.0.0.102'
  1365. },
  1366. 'kalahari' => {
  1367. 'osversion' => '2.0.34',
  1368. 'osname' => 'linux',
  1369. 'address' => [ '10.0.0.103', '10.0.1.103' ]
  1370. }
  1371. }
  1372. }
  1373. Your script could then access the name of the log directory like this:
  1374. print $config->{logdir};
  1375. similarly, the second address on the server 'kalahari' could be referenced as:
  1376. print $config->{server}->{kalahari}->{address}->[1];
  1377. What could be simpler? (Rhetorical).
  1378. For simple requirements, that's really all there is to it. If you want to
  1379. store your XML in a different directory or file, or pass it in as a string or
  1380. even pass it in via some derivative of an IO::Handle, you'll need to check out
  1381. L<"OPTIONS">. If you want to turn off or tweak the array folding feature (that
  1382. neat little transformation that produced $config->{server}) you'll find options
  1383. for that as well.
  1384. If you want to generate XML (for example to write a modified version of
  1385. $config back out as XML), check out C<XMLout()>.
  1386. If your needs are not so simple, this may not be the module for you. In that
  1387. case, you might want to read L<"WHERE TO FROM HERE?">.
  1388. =head1 DESCRIPTION
  1389. The XML::Simple module provides a simple API layer on top of an underlying XML
  1390. parsing module (either XML::Parser or one of the SAX2 parser modules). Two
  1391. functions are exported: C<XMLin()> and C<XMLout()>. Note: you can explicity
  1392. request the lower case versions of the function names: C<xml_in()> and
  1393. C<xml_out()>.
  1394. The simplest approach is to call these two functions directly, but an
  1395. optional object oriented interface (see L<"OPTIONAL OO INTERFACE"> below)
  1396. allows them to be called as methods of an B<XML::Simple> object. The object
  1397. interface can also be used at either end of a SAX pipeline.
  1398. =head2 XMLin()
  1399. Parses XML formatted data and returns a reference to a data structure which
  1400. contains the same information in a more readily accessible form. (Skip
  1401. down to L<"EXAMPLES"> below, for more sample code).
  1402. C<XMLin()> accepts an optional XML specifier followed by zero or more 'name =>
  1403. value' option pairs. The XML specifier can be one of the following:
  1404. =over 4
  1405. =item A filename
  1406. If the filename contains no directory components C<XMLin()> will look for the
  1407. file in each directory in the SearchPath (see L<"OPTIONS"> below) or in the
  1408. current directory if the SearchPath option is not defined. eg:
  1409. $ref = XMLin('/etc/params.xml');
  1410. Note, the filename '-' can be used to parse from STDIN.
  1411. =item undef
  1412. If there is no XML specifier, C<XMLin()> will check the script directory and
  1413. each of the SearchPath directories for a file with the same name as the script
  1414. but with the extension '.xml'. Note: if you wish to specify options, you
  1415. must specify the value 'undef'. eg:
  1416. $ref = XMLin(undef, ForceArray => 1);
  1417. =item A string of XML
  1418. A string containing XML (recognised by the presence of '<' and '>' characters)
  1419. will be parsed