Simple.pm 95 KB

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