1XML::Simple::FAQ(3)   User Contributed Perl Documentation  XML::Simple::FAQ(3)
2
3
4

NAME

6       XML::Simple::FAQ - Frequently Asked Questions about XML::Simple
7

Basics

9   What should I use XML::Simple for?
10       Nothing!
11
12       It's as simple as that.
13
14       Choose a better module. See Perl XML::LibXML by Example
15       <http://grantm.github.io/perl-libxml-by-example/> for a gentle
16       introduction to XML::LibXML with lots of examples.
17
18   What was XML::Simple designed to be used for?
19       XML::Simple is a Perl module that was originally developed as a tool
20       for reading and writing configuration data in XML format.  You could
21       use it for other purposes that involve storing and retrieving
22       structured data in XML but it's likely to be a frustrating experience.
23
24   Why store configuration data in XML anyway?
25       It seemed like a good idea at the time.  Now, I use and recommend
26       Config::General which uses a format similar to that used by the Apache
27       web server.  This is easier to read than XML while still allowing
28       advanced concepts such as nested sections.
29
30       At the time XML::Simple was written, the advantages of using XML format
31       for configuration data were thought to include:
32
33       •   Using existing XML parsing tools requires less development time, is
34           easier and more robust than developing your own config file parsing
35           code
36
37       •   XML can represent relationships between pieces of data, such as
38           nesting of sections to arbitrary levels (not easily done with .INI
39           files for example)
40
41       •   XML is basically just text, so you can easily edit a config file
42           (easier than editing a Win32 registry)
43
44       •   XML provides standard solutions for handling character sets and
45           encoding beyond basic ASCII (important for internationalization)
46
47       •   If it becomes necessary to change your configuration file format,
48           there are many tools available for performing transformations on
49           XML files
50
51       •   XML is an open standard (the world does not need more proprietary
52           binary file formats)
53
54       •   Taking the extra step of developing a DTD allows the format of
55           configuration files to be validated before your program reads them
56           (not directly supported by XML::Simple)
57
58       •   Combining a DTD with a good XML editor can give you a GUI config
59           editor for minimal coding effort
60
61   What isn't XML::Simple good for?
62       The main limitation of XML::Simple is that it does not work with 'mixed
63       content' (see the next question).  If you consider your XML files
64       contain marked up text rather than structured data, you should probably
65       use another module.
66
67       If your source XML documents change regularly, it's likely that you
68       will experience intermittent failures.  In particular, failure to
69       properly use the ForceArray and KeyAttr options will produce code that
70       works when you get a list of elements with the same name, but fails
71       when there's only one item in the list.  These types of problems can be
72       avoided by not using XML::Simple in the first place.
73
74       If you are working with very large XML files, XML::Simple's approach of
75       representing the whole file in memory as a 'tree' data structure may
76       not be suitable.
77
78   What is mixed content?
79       Consider this example XML:
80
81         <document>
82           <para>This is <em>mixed</em> content.</para>
83         </document>
84
85       This is said to be mixed content, because the <para> element contains
86       both character data (text content) and nested elements.
87
88       Here's some more XML:
89
90         <person>
91           <first_name>Joe</first_name>
92           <last_name>Bloggs</last_name>
93           <dob>25-April-1969</dob>
94         </person>
95
96       This second example is not generally considered to be mixed content.
97       The <first_name>, <last_name> and <dob> elements contain only character
98       data and the  <person> element contains only nested elements.  (Note:
99       Strictly speaking, the whitespace between the nested elements is
100       character data, but it is ignored by XML::Simple).
101
102   Why doesn't XML::Simple handle mixed content?
103       Because if it did, it would no longer be simple :-)
104
105       Seriously though, there are plenty of excellent modules that allow you
106       to work with mixed content in a variety of ways.  Handling mixed
107       content correctly is not easy and by ignoring these issues, XML::Simple
108       is able to present an API without a steep learning curve.
109
110   Which Perl modules do handle mixed content?
111       Every one of them except XML::Simple :-)
112
113       If you're looking for a recommendation, I'd suggest you look at the
114       Perl-XML FAQ at:
115
116         http://perl-xml.sourceforge.net/faq/
117

Installation

119   How do I install XML::Simple?
120       If you're running ActiveState Perl, or Strawberry Perl
121       <http://strawberryperl.com/> you've probably already got XML::Simple
122       and therefore do not need to install it at all.  But you probably also
123       have XML::LibXML, which is a much better module, so just use that.
124
125       If you do need to install XML::Simple, you'll need to install an XML
126       parser module first.  Install either XML::Parser (which you may have
127       already) or XML::SAX.  If you install both, XML::SAX will be used by
128       default.
129
130       Once you have a parser installed ...
131
132       On Unix systems, try:
133
134         perl -MCPAN -e 'install XML::Simple'
135
136       If that doesn't work, download the latest distribution from
137       ftp://ftp.cpan.org/pub/CPAN/authors/id/G/GR/GRANTM , unpack it and run
138       these commands:
139
140         perl Makefile.PL
141         make
142         make test
143         make install
144
145       On Win32, if you have a recent build of ActiveState Perl (618 or
146       better) try this command:
147
148         ppm install XML::Simple
149
150       If that doesn't work, you really only need the Simple.pm file, so
151       extract it from the .tar.gz file (eg: using WinZIP) and save it in the
152       \site\lib\XML directory under your Perl installation (typically
153       C:\Perl).
154
155   I'm trying to install XML::Simple and 'make test' fails
156       Is the directory where you've unpacked XML::Simple mounted from a file
157       server using NFS, SMB or some other network file sharing?  If so, that
158       may cause errors in the following test scripts:
159
160         3_Storable.t
161         4_MemShare.t
162         5_MemCopy.t
163
164       The test suite is designed to exercise the boundary conditions of all
165       XML::Simple's functionality and these three scripts exercise the
166       caching functions.  If XML::Simple is asked to parse a file for which
167       it has a cached copy of a previous parse, then it compares the
168       timestamp on the XML file with the timestamp on the cached copy.  If
169       the cached copy is *newer* then it will be used.  If the cached copy is
170       older or the same age then the file is re-parsed.  The test scripts
171       will get confused by networked filesystems if the workstation and
172       server system clocks are not synchronised (to the second).
173
174       If you get an error in one of these three test scripts but you don't
175       plan to use the caching options (they're not enabled by default), then
176       go right ahead and run 'make install'.  If you do plan to use caching,
177       then try unpacking the distribution on local disk and doing the
178       build/test there.
179
180       It's probably not a good idea to use the caching options with networked
181       filesystems in production.  If the file server's clock is ahead of the
182       local clock, XML::Simple will re-parse files when it could have used
183       the cached copy.  However if the local clock is ahead of the file
184       server clock and a file is changed immediately after it is cached, the
185       old cached copy will be used.
186
187       Is one of the three test scripts (above) failing but you're not running
188       on a network filesystem?  Are you running Win32?  If so, you may be
189       seeing a bug in Win32 where writes to a file do not affect its
190       modification timestamp.
191
192       If none of these scenarios match your situation, please confirm you're
193       running the latest version of XML::Simple and then email the output of
194       'make test' to me at grantm@cpan.org
195
196   Why is XML::Simple so slow?
197       If you find that XML::Simple is very slow reading XML, the most likely
198       reason is that you have XML::SAX installed but no additional SAX parser
199       module.  The XML::SAX distribution includes an XML parser written
200       entirely in Perl.  This is very portable but not very fast.  For better
201       performance install either XML::SAX::Expat or XML::LibXML.
202

Usage

204   How do I use XML::Simple?
205       If you don't know how to use XML::Simple then the best approach is to
206       learn to use XML::LibXML <http://grantm.github.io/perl-libxml-by-
207       example/> instead.  Stop reading this document and use that one
208       instead.
209
210       If you are determined to use XML::Simple, it come with copious
211       documentation, so read that.
212
213   There are so many options, which ones do I really need to know about?
214       Although you can get by without using any options, you shouldn't even
215       consider using XML::Simple in production until you know what these two
216       options do:
217
218       •   forcearray
219
220       •   keyattr
221
222       The reason you really need to read about them is because the default
223       values for these options will trip you up if you don't.  Although
224       everyone agrees that these defaults are not ideal, there is not wide
225       agreement on what they should be changed to.  The answer therefore is
226       to read about them (see below) and select values which are right for
227       you.
228
229   What is the forcearray option all about?
230       Consider this XML in a file called ./person.xml:
231
232         <person>
233           <first_name>Joe</first_name>
234           <last_name>Bloggs</last_name>
235           <hobbie>bungy jumping</hobbie>
236           <hobbie>sky diving</hobbie>
237           <hobbie>knitting</hobbie>
238         </person>
239
240       You could read it in with this line:
241
242         my $person = XMLin('./person.xml');
243
244       Which would give you a data structure like this:
245
246         $person = {
247           'first_name' => 'Joe',
248           'last_name'  => 'Bloggs',
249           'hobbie'     => [ 'bungy jumping', 'sky diving', 'knitting' ]
250         };
251
252       The <first_name> and <last_name> elements are represented as simple
253       scalar values which you could refer to like this:
254
255         print "$person->{first_name} $person->{last_name}\n";
256
257       The <hobbie> elements are represented as an array - since there is more
258       than one.  You could refer to the first one like this:
259
260         print $person->{hobbie}->[0], "\n";
261
262       Or the whole lot like this:
263
264         print join(', ', @{$person->{hobbie}} ), "\n";
265
266       The catch is, that these last two lines of code will only work for
267       people who have more than one hobbie.  If there is only one <hobbie>
268       element, it will be represented as a simple scalar (just like
269       <first_name> and <last_name>).  Which might lead you to write code like
270       this:
271
272         if(ref($person->{hobbie})) {
273           print join(', ', @{$person->{hobbie}} ), "\n";
274         }
275         else {
276           print $person->{hobbie}, "\n";
277         }
278
279       Don't do that.
280
281       One alternative approach is to set the forcearray option to a true
282       value:
283
284         my $person = XMLin('./person.xml', forcearray => 1);
285
286       Which will give you a data structure like this:
287
288         $person = {
289           'first_name' => [ 'Joe' ],
290           'last_name'  => [ 'Bloggs' ],
291           'hobbie'     => [ 'bungy jumping', 'sky diving', 'knitting' ]
292         };
293
294       Then you can use this line to refer to all the list of hobbies even if
295       there was only one:
296
297         print join(', ', @{$person->{hobbie}} ), "\n";
298
299       The downside of this approach is that the <first_name> and <last_name>
300       elements will also always be represented as arrays even though there
301       will never be more than one:
302
303         print "$person->{first_name}->[0] $person->{last_name}->[0]\n";
304
305       This might be OK if you change the XML to use attributes for things
306       that will always be singular and nested elements for things that may be
307       plural:
308
309         <person first_name="Jane" last_name="Bloggs">
310           <hobbie>motorcycle maintenance</hobbie>
311         </person>
312
313       On the other hand, if you prefer not to use attributes, then you could
314       specify that any <hobbie> elements should always be represented as
315       arrays and all other nested elements should be simple scalar values
316       unless there is more than one:
317
318         my $person = XMLin('./person.xml', forcearray => [ 'hobbie' ]);
319
320       The forcearray option accepts a list of element names which should
321       always be forced to an array representation:
322
323         forcearray => [ qw(hobbie qualification childs_name) ]
324
325       See the XML::Simple manual page for more information.
326
327   What is the keyattr option all about?
328       Consider this sample XML:
329
330         <catalog>
331           <part partnum="1842334" desc="High pressure flange" price="24.50" />
332           <part partnum="9344675" desc="Threaded gasket"      price="9.25" />
333           <part partnum="5634896" desc="Low voltage washer"   price="12.00" />
334         </catalog>
335
336       You could slurp it in with this code:
337
338         my $catalog = XMLin('./catalog.xml');
339
340       Which would return a data structure like this:
341
342         $catalog = {
343             'part' => [
344                 {
345                   'partnum' => '1842334',
346                   'desc'    => 'High pressure flange',
347                   'price'   => '24.50'
348                 },
349                 {
350                   'partnum' => '9344675',
351                   'desc'    => 'Threaded gasket',
352                   'price'   => '9.25'
353                 },
354                 {
355                   'partnum' => '5634896',
356                   'desc'    => 'Low voltage washer',
357                   'price'   => '12.00'
358                 }
359             ]
360         };
361
362       Then you could access the description of the first part in the catalog
363       with this code:
364
365         print $catalog->{part}->[0]->{desc}, "\n";
366
367       However, if you wanted to access the description of the part with the
368       part number of "9344675" then you'd have to code a loop like this:
369
370         foreach my $part (@{$catalog->{part}}) {
371           if($part->{partnum} eq '9344675') {
372             print $part->{desc}, "\n";
373             last;
374           }
375         }
376
377       The knowledge that each <part> element has a unique partnum attribute
378       allows you to eliminate this search.  You can pass this knowledge on to
379       XML::Simple like this:
380
381         my $catalog = XMLin($xml, keyattr => ['partnum']);
382
383       Which will return a data structure like this:
384
385         $catalog = {
386           'part' => {
387             '5634896' => { 'desc' => 'Low voltage washer',   'price' => '12.00' },
388             '1842334' => { 'desc' => 'High pressure flange', 'price' => '24.50' },
389             '9344675' => { 'desc' => 'Threaded gasket',      'price' => '9.25'  }
390           }
391         };
392
393       XML::Simple has been able to transform $catalog->{part} from an
394       arrayref to a hashref (keyed on partnum).  This transformation is
395       called 'array folding'.
396
397       Through the use of array folding, you can now index directly to the
398       description of the part you want:
399
400         print $catalog->{part}->{9344675}->{desc}, "\n";
401
402       The 'keyattr' option also enables array folding when the unique key is
403       in a nested element rather than an attribute.  eg:
404
405         <catalog>
406           <part>
407             <partnum>1842334</partnum>
408             <desc>High pressure flange</desc>
409             <price>24.50</price>
410           </part>
411           <part>
412             <partnum>9344675</partnum>
413             <desc>Threaded gasket</desc>
414             <price>9.25</price>
415           </part>
416           <part>
417             <partnum>5634896</partnum>
418             <desc>Low voltage washer</desc>
419             <price>12.00</price>
420           </part>
421         </catalog>
422
423       See the XML::Simple manual page for more information.
424
425   So what's the catch with 'keyattr'?
426       One thing to watch out for is that you might get array folding even if
427       you don't supply the keyattr option.  The default value for this option
428       is:
429
430         [ 'name', 'key', 'id']
431
432       Which means if your XML elements have a 'name', 'key' or 'id' attribute
433       (or nested element) then they may get folded on those values.  This
434       means that you can take advantage of array folding simply through
435       careful choice of attribute names.  On the hand, if you really don't
436       want array folding at all, you'll need to set 'key attr to an empty
437       list:
438
439         my $ref = XMLin($xml, keyattr => []);
440
441       A second 'gotcha' is that array folding only works on arrays.  That
442       might seem obvious, but if there's only one record in your XML and you
443       didn't set the 'forcearray' option then it won't be represented as an
444       array and consequently won't get folded into a hash.  The moral is that
445       if you're using array folding, you should always turn on the forcearray
446       option.
447
448       You probably want to be as specific as you can be too.  For instance,
449       the safest way to parse the <catalog> example above would be:
450
451         my $catalog = XMLin($xml, keyattr => { part => 'partnum'},
452                                   forcearray => ['part']);
453
454       By using the hashref for keyattr, you can specify that only <part>
455       elements should be folded on the 'partnum' attribute (and that the
456       <part> elements should not be folded on any other attribute).
457
458       By supplying a list of element names for forcearray, you're ensuring
459       that folding will work even if there's only one <part>.  You're also
460       ensuring that if the 'partnum' unique key is supplied in a nested
461       element then that element won't get forced to an array too.
462
463   How do I know what my data structure should look like?
464       The rules are fairly straightforward:
465
466       •   each element gets represented as a hash
467
468       •   unless it contains only text, in which case it'll be a simple
469           scalar value
470
471       •   or unless there's more than one element with the same name, in
472           which case they'll be represented as an array
473
474       •   unless you've got array folding enabled, in which case they'll be
475           folded into a hash
476
477       •   empty elements (no text contents and no attributes) will either be
478           represented as an empty hash, an empty string or undef - depending
479           on the value of the 'suppressempty' option.
480
481       If you're in any doubt, use Data::Dumper, eg:
482
483         use XML::Simple;
484         use Data::Dumper;
485
486         my $ref = XMLin($xml);
487
488         print Dumper($ref);
489
490   I'm getting 'Use of uninitialized value' warnings
491       You're probably trying to index into a non-existant hash key - try
492       Data::Dumper.
493
494   I'm getting a 'Not an ARRAY reference' error
495       Something that you expect to be an array is not.  The two most likely
496       causes are that you forgot to use 'forcearray' or that the array got
497       folded into a hash - try Data::Dumper.
498
499   I'm getting a 'No such array field' error
500       Something that you expect to be a hash is actually an array.  Perhaps
501       array folding failed because one element was missing the key attribute
502       - try Data::Dumper.
503
504   I'm getting an 'Out of memory' error
505       Something in the data structure is not as you expect and Perl may be
506       trying unsuccessfully to autovivify things - try Data::Dumper.
507
508       If you're already using Data::Dumper, try calling Dumper() immediately
509       after XMLin() - ie: before you attempt to access anything in the data
510       structure.
511
512   My element order is getting jumbled up
513       If you read an XML file with XMLin() and then write it back out with
514       XMLout(), the order of the elements will likely be different.
515       (However, if you read the file back in with XMLin() you'll get the same
516       Perl data structure).
517
518       The reordering happens because XML::Simple uses hashrefs to store your
519       data and Perl hashes do not really have any order.
520
521       It is possible that a future version of XML::Simple will use
522       Tie::IxHash to store the data in hashrefs which do retain the order.
523       However this will not fix all cases of element order being lost.
524
525       If your application really is sensitive to element order, don't use
526       XML::Simple (and don't put order-sensitive values in attributes).
527
528   XML::Simple turns nested elements into attributes
529       If you read an XML file with XMLin() and then write it back out with
530       XMLout(), some data which was originally stored in nested elements may
531       end up in attributes.  (However, if you read the file back in with
532       XMLin() you'll get the same Perl data structure).
533
534       There are a number of ways you might handle this:
535
536       •   use the 'forcearray' option with XMLin()
537
538       •   use the 'noattr' option with XMLout()
539
540       •   live with it
541
542       •   don't use XML::Simple
543
544   Why does XMLout() insert <name> elements (or attributes)?
545       Try setting keyattr => [].
546
547       When you call XMLin() to read XML, the 'keyattr' option controls
548       whether arrays get 'folded' into hashes.  Similarly, when you call
549       XMLout(), the 'keyattr' option controls whether hashes get 'unfolded'
550       into arrays.  As described above, 'keyattr' is enabled by default.
551
552   Why are empty elements represented as empty hashes?
553       An element is always represented as a hash unless it contains only
554       text, in which case it is represented as a scalar string.
555
556       If you would prefer empty elements to be represented as empty strings
557       or the undefined value, set the 'suppressempty' option to '' or undef
558       respectively.
559
560   Why is ParserOpts deprecated?
561       The "ParserOpts" option is a remnant of the time when XML::Simple only
562       worked with the XML::Parser API.  Its value is completely ignored if
563       you're using a SAX parser, so writing code which relied on it would bar
564       you from taking advantage of SAX.
565
566       Even if you are using XML::Parser, it is seldom necessary to pass
567       options to the parser object.  A number of people have written to say
568       they use this option to set XML::Parser's "ProtocolEncoding" option.
569       Don't do that, it's wrong, Wrong, WRONG!  Fix the XML document so that
570       it's well-formed and you won't have a problem.
571
572       Having said all of that, as long as XML::Simple continues to support
573       the XML::Parser API, this option will not be removed.  There are
574       currently no plans to remove support for the XML::Parser API.
575
576
577
578perl v5.36.0                      2023-01-20               XML::Simple::FAQ(3)
Impressum