1XML::Simple::FAQ(3) User Contributed Perl Documentation XML::Simple::FAQ(3)
2
3
4
7 What is XML::Simple designed to be used for?
8
9 XML::Simple is a Perl module that was originally developed as a tool
10 for reading and writing configuration data in XML format. You can use
11 it for many other purposes that involve storing and retrieving struc‐
12 tured data in XML.
13
14 You might also find XML::Simple a good starting point for playing with
15 XML from Perl. It doesn't have a steep learning curve and if you out‐
16 grow its capabilities there are plenty of other Perl/XML modules to
17 'step up' to.
18
19 Why store configuration data in XML anyway?
20
21 The many advantages of using XML format for configuration data include:
22
23 · Using existing XML parsing tools requires less development time, is
24 easier and more robust than developing your own config file parsing
25 code
26
27 · XML can represent relationships between pieces of data, such as
28 nesting of sections to arbitrary levels (not easily done with .INI
29 files for example)
30
31 · XML is basically just text, so you can easily edit a config file
32 (easier than editing a Win32 registry)
33
34 · XML provides standard solutions for handling character sets and
35 encoding beyond basic ASCII (important for internationalization)
36
37 · If it becomes necessary to change your configuration file format,
38 there are many tools available for performing transformations on
39 XML files
40
41 · XML is an open standard (the world does not need more proprietary
42 binary file formats)
43
44 · Taking the extra step of developing a DTD allows the format of con‐
45 figuration files to be validated before your program reads them
46 (not directly supported by XML::Simple)
47
48 · Combining a DTD with a good XML editor can give you a GUI config
49 editor for minimal coding effort
50
51 What isn't XML::Simple good for?
52
53 The main limitation of XML::Simple is that it does not work with 'mixed
54 content' (see the next question). If you consider your XML files con‐
55 tain marked up text rather than structured data, you should probably
56 use another module.
57
58 If you are working with very large XML files, XML::Simple's approach of
59 representing the whole file in memory as a 'tree' data structure may
60 not be suitable.
61
62 What is mixed content?
63
64 Consider this example XML:
65
66 <document>
67 <para>This is <em>mixed</em> content.</para>
68 </document>
69
70 This is said to be mixed content, because the <para> element contains
71 both character data (text content) and nested elements.
72
73 Here's some more XML:
74
75 <person>
76 <first_name>Joe</first_name>
77 <last_name>Bloggs</last_name>
78 <dob>25-April-1969</dob>
79 </person>
80
81 This second example is not generally considered to be mixed content.
82 The <first_name>, <last_name> and <dob> elements contain only character
83 data and the <person> element contains only nested elements. (Note:
84 Strictly speaking, the whitespace between the nested elements is char‐
85 acter data, but it is ignored by XML::Simple).
86
87 Why doesn't XML::Simple handle mixed content?
88
89 Because if it did, it would no longer be simple :-)
90
91 Seriously though, there are plenty of excellent modules that allow you
92 to work with mixed content in a variety of ways. Handling mixed con‐
93 tent correctly is not easy and by ignoring these issues, XML::Simple is
94 able to present an API without a steep learning curve.
95
96 Which Perl modules do handle mixed content?
97
98 Every one of them except XML::Simple :-)
99
100 If you're looking for a recommendation, I'd suggest you look at the
101 Perl-XML FAQ at:
102
103 http://perl-xml.sourceforge.net/faq/
104
106 How do I install XML::Simple?
107
108 If you're running ActiveState Perl, you've probably already got
109 XML::Simple (although you may want to upgrade to version 1.09 or better
110 for SAX support).
111
112 If you do need to install XML::Simple, you'll need to install an XML
113 parser module first. Install either XML::Parser (which you may have
114 already) or XML::SAX. If you install both, XML::SAX will be used by
115 default.
116
117 Once you have a parser installed ...
118
119 On Unix systems, try:
120
121 perl -MCPAN -e 'install XML::Simple'
122
123 If that doesn't work, download the latest distribution from
124 ftp://ftp.cpan.org/pub/CPAN/authors/id/G/GR/GRANTM , unpack it and run
125 these commands:
126
127 perl Makefile.PL
128 make
129 make test
130 make install
131
132 On Win32, if you have a recent build of ActiveState Perl (618 or bet‐
133 ter) try this command:
134
135 ppm install XML::Simple
136
137 If that doesn't work, you really only need the Simple.pm file, so
138 extract it from the .tar.gz file (eg: using WinZIP) and save it in the
139 \site\lib\XML directory under your Perl installation (typically
140 C:\Perl).
141
142 I'm trying to install XML::Simple and 'make test' fails
143
144 Is the directory where you've unpacked XML::Simple mounted from a file
145 server using NFS, SMB or some other network file sharing? If so, that
146 may cause errors in the the following test scripts:
147
148 3_Storable.t
149 4_MemShare.t
150 5_MemCopy.t
151
152 The test suite is designed to exercise the boundary conditions of all
153 XML::Simple's functionality and these three scripts exercise the
154 caching functions. If XML::Simple is asked to parse a file for which
155 it has a cached copy of a previous parse, then it compares the time‐
156 stamp on the XML file with the timestamp on the cached copy. If the
157 cached copy is *newer* then it will be used. If the cached copy is
158 older or the same age then the file is re-parsed. The test scripts
159 will get confused by networked filesystems if the workstation and
160 server system clocks are not synchronised (to the second).
161
162 If you get an error in one of these three test scripts but you don't
163 plan to use the caching options (they're not enabled by default), then
164 go right ahead and run 'make install'. If you do plan to use caching,
165 then try unpacking the distribution on local disk and doing the
166 build/test there.
167
168 It's probably not a good idea to use the caching options with networked
169 filesystems in production. If the file server's clock is ahead of the
170 local clock, XML::Simple will re-parse files when it could have used
171 the cached copy. However if the local clock is ahead of the file
172 server clock and a file is changed immediately after it is cached, the
173 old cached copy will be used.
174
175 Is one of the three test scripts (above) failing but you're not running
176 on a network filesystem? Are you running Win32? If so, you may be
177 seeing a bug in Win32 where writes to a file do not affect its modfica‐
178 tion timestamp.
179
180 If none of these scenarios match your situation, please confirm you're
181 running the latest version of XML::Simple and then email the output of
182 'make test' to me at grantm@cpan.org
183
184 Why is XML::Simple so slow?
185
186 If you find that XML::Simple is very slow reading XML, the most likely
187 reason is that you have XML::SAX installed but no additional SAX parser
188 module. The XML::SAX distribution includes an XML parser written
189 entirely in Perl. This is very portable but not very fast. For better
190 performance install either XML::SAX::Expat or XML::LibXML.
191
193 How do I use XML::Simple?
194
195 If you had an XML document called /etc/appconfig/foo.xml you could
196 'slurp' it into a simple data structure (typically a hashref) with
197 these lines of code:
198
199 use XML::Simple;
200
201 my $config = XMLin('/etc/appconfig/foo.xml');
202
203 The XMLin() function accepts options after the filename.
204
205 There are so many options, which ones do I really need to know about?
206
207 Although you can get by without using any options, you shouldn't even
208 consider using XML::Simple in production until you know what these two
209 options do:
210
211 · forcearray
212
213 · keyattr
214
215 The reason you really need to read about them is because the default
216 values for these options will trip you up if you don't. Although
217 everyone agrees that these defaults are not ideal, there is not wide
218 agreement on what they should be changed to. The answer therefore is
219 to read about them (see below) and select values which are right for
220 you.
221
222 What is the forcearray option all about?
223
224 Consider this XML in a file called ./person.xml:
225
226 <person>
227 <first_name>Joe</first_name>
228 <last_name>Bloggs</last_name>
229 <hobbie>bungy jumping</hobbie>
230 <hobbie>sky diving</hobbie>
231 <hobbie>knitting</hobbie>
232 </person>
233
234 You could read it in with this line:
235
236 my $person = XMLin('./person.xml');
237
238 Which would give you a data structure like this:
239
240 $person = {
241 'first_name' => 'Joe',
242 'last_name' => 'Bloggs',
243 'hobbie' => [ 'bungy jumping', 'sky diving', 'knitting' ]
244 };
245
246 The <first_name> and <last_name> elements are represented as simple
247 scalar values which you could refer to like this:
248
249 print "$person->{first_name} $person->{last_name}\n";
250
251 The <hobbie> elements are represented as an array - since there is more
252 than one. You could refer to the first one like this:
253
254 print $person->{hobbie}->[0], "\n";
255
256 Or the whole lot like this:
257
258 print join(', ', @{$person->{hobbie}} ), "\n";
259
260 The catch is, that these last two lines of code will only work for peo‐
261 ple who have more than one hobbie. If there is only one <hobbie> ele‐
262 ment, it will be represented as a simple scalar (just like <first_name>
263 and <last_name>). Which might lead you to write code like this:
264
265 if(ref($person->{hobbie})) {
266 print join(', ', @{$person->{hobbie}} ), "\n";
267 }
268 else {
269 print $person->{hobbie}, "\n";
270 }
271
272 Don't do that.
273
274 One alternative approach is to set the forcearray option to a true
275 value:
276
277 my $person = XMLin('./person.xml', forcearray => 1);
278
279 Which will give you a data structure like this:
280
281 $person = {
282 'first_name' => [ 'Joe' ],
283 'last_name' => [ 'Bloggs' ],
284 'hobbie' => [ 'bungy jumping', 'sky diving', 'knitting' ]
285 };
286
287 Then you can use this line to refer to all the list of hobbies even if
288 there was only one:
289
290 print join(', ', @{$person->{hobbie}} ), "\n";
291
292 The downside of this approach is that the <first_name> and <last_name>
293 elements will also always be represented as arrays even though there
294 will never be more than one:
295
296 print "$person->{first_name}->[0] $person->{last_name}->[0]\n";
297
298 This might be OK if you change the XML to use attributes for things
299 that will always be singular and nested elements for things that may be
300 plural:
301
302 <person first_name="Jane" last_name="Bloggs">
303 <hobbie>motorcycle maintenance</hobbie>
304 </person>
305
306 On the other hand, if you prefer not to use attributes, then you could
307 specify that any <hobbie> elements should always be represented as
308 arrays and all other nested elements should be simple scalar values
309 unless there is more than one:
310
311 my $person = XMLin('./person.xml', forcearray => [ 'hobbie' ]);
312
313 The forcearray option accepts a list of element names which should
314 always be forced to an array representation:
315
316 forcearray => [ qw(hobbie qualification childs_name) ]
317
318 See the XML::Simple manual page for more information.
319
320 What is the keyattr option all about?
321
322 Consider this sample XML:
323
324 <catalog>
325 <part partnum="1842334" desc="High pressure flange" price="24.50" />
326 <part partnum="9344675" desc="Threaded gasket" price="9.25" />
327 <part partnum="5634896" desc="Low voltage washer" price="12.00" />
328 </catalog>
329
330 You could slurp it in with this code:
331
332 my $catalog = XMLin('./catalog.xml');
333
334 Which would return a data structure like this:
335
336 $catalog = {
337 'part' => [
338 {
339 'partnum' => '1842334',
340 'desc' => 'High pressure flange',
341 'price' => '24.50'
342 },
343 {
344 'partnum' => '9344675',
345 'desc' => 'Threaded gasket',
346 'price' => '9.25'
347 },
348 {
349 'partnum' => '5634896',
350 'desc' => 'Low voltage washer',
351 'price' => '12.00'
352 }
353 ]
354 };
355
356 Then you could access the description of the first part in the catalog
357 with this code:
358
359 print $catalog->{part}->[0]->{desc}, "\n";
360
361 However, if you wanted to access the description of the part with the
362 part number of "9344675" then you'd have to code a loop like this:
363
364 foreach my $part (@{$catalog->{part}}) {
365 if($part->{partnum} eq '9344675') {
366 print $part->{desc}, "\n";
367 last;
368 }
369 }
370
371 The knowledge that each <part> element has a unique partnum attribute
372 allows you to eliminate this search. You can pass this knowledge on to
373 XML::Simple like this:
374
375 my $catalog = XMLin($xml, keyattr => ['partnum']);
376
377 Which will return a data structure like this:
378
379 $catalog = {
380 'part' => {
381 '5634896' => { 'desc' => 'Low voltage washer', 'price' => '12.00' },
382 '1842334' => { 'desc' => 'High pressure flange', 'price' => '24.50' },
383 '9344675' => { 'desc' => 'Threaded gasket', 'price' => '9.25' }
384 }
385 };
386
387 XML::Simple has been able to transform $catalog->{part} from an
388 arrayref to a hashref (keyed on partnum). This transformation is
389 called 'array folding'.
390
391 Through the use of array folding, you can now index directly to the
392 description of the part you want:
393
394 print $catalog->{part}->{9344675}->{desc}, "\n";
395
396 The 'keyattr' option also enables array folding when the unique key is
397 in a nested element rather than an attribute. eg:
398
399 <catalog>
400 <part>
401 <partnum>1842334</partnum>
402 <desc>High pressure flange</desc>
403 <price>24.50</price>
404 </part>
405 <part>
406 <partnum>9344675</partnum>
407 <desc>Threaded gasket</desc>
408 <price>9.25</price>
409 </part>
410 <part>
411 <partnum>5634896</partnum>
412 <desc>Low voltage washer</desc>
413 <price>12.00</price>
414 </part>
415 </catalog>
416
417 See the XML::Simple manual page for more information.
418
419 So what's the catch with 'keyattr'?
420
421 One thing to watch out for is that you might get array folding even if
422 you don't supply the keyattr option. The default value for this option
423 is:
424
425 [ 'name', 'key', 'id']
426
427 Which means if your XML elements have a 'name', 'key' or 'id' attribute
428 (or nested element) then they may get folded on those values. This
429 means that you can take advantage of array folding simply through care‐
430 ful choice of attribute names. On the hand, if you really don't want
431 array folding at all, you'll need to set 'key attr to an empty list:
432
433 my $ref = XMLin($xml, keyattr => []);
434
435 A second 'gotcha' is that array folding only works on arrays. That
436 might seem obvious, but if there's only one record in your XML and you
437 didn't set the 'forcearray' option then it won't be represented as an
438 array and consequently won't get folded into a hash. The moral is that
439 if you're using array folding, you should always turn on the forcearray
440 option.
441
442 You probably want to be as specific as you can be too. For instance,
443 the safest way to parse the <catalog> example above would be:
444
445 my $catalog = XMLin($xml, keyattr => { part => 'partnum'},
446 forcearray => ['part']);
447
448 By using the hashref for keyattr, you can specify that only <part> ele‐
449 ments should be folded on the 'partnum' attribute (and that the <part>
450 elements should not be folded on any other attribute).
451
452 By supplying a list of element names for forcearray, you're ensuring
453 that folding will work even if there's only one <part>. You're also
454 ensuring that if the 'partnum' unique key is supplied in a nested ele‐
455 ment then that element won't get forced to an array too.
456
457 How do I know what my data structure should look like?
458
459 The rules are fairly straightforward:
460
461 · each element gets represented as a hash
462
463 · unless it contains only text, in which case it'll be a simple
464 scalar value
465
466 · or unless there's more than one element with the same name, in
467 which case they'll be represented as an array
468
469 · unless you've got array folding enabled, in which case they'll be
470 folded into a hash
471
472 · empty elements (no text contents and no attributes) will either be
473 represented as an empty hash, an empty string or undef - depending
474 on the value of the 'suppressempty' option.
475
476 If you're in any doubt, use Data::Dumper, eg:
477
478 use XML::Simple;
479 use Data::Dumper;
480
481 my $ref = XMLin($xml);
482
483 print Dumper($ref);
484
485 I'm getting 'Use of uninitialized value' warnings
486
487 You're probably trying to index into a non-existant hash key - try
488 Data::Dumper.
489
490 I'm getting a 'Not an ARRAY reference' error
491
492 Something that you expect to be an array is not. The two most likely
493 causes are that you forgot to use 'forcearray' or that the array got
494 folded into a hash - try Data::Dumper.
495
496 I'm getting a 'No such array field' error
497
498 Something that you expect to be a hash is actually an array. Perhaps
499 array folding failed because one element was missing the key attribute
500 - try Data::Dumper.
501
502 I'm getting an 'Out of memory' error
503
504 Something in the data structure is not as you expect and Perl may be
505 trying unsuccessfully to autovivify things - try Data::Dumper.
506
507 If you're already using Data::Dumper, try calling Dumper() immediately
508 after XMLin() - ie: before you attempt to access anything in the data
509 structure.
510
511 My element order is getting jumbled up
512
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. (How‐
515 ever, 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
530 If you read an XML file with XMLin() and then write it back out with
531 XMLout(), some data which was originally stored in nested elements may
532 end up in attributes. (However, if you read the file back in with
533 XMLin() you'll get the same Perl data structure).
534
535 There are a number of ways you might handle this:
536
537 · use the 'forcearray' option with XMLin()
538
539 · use the 'noattr' option with XMLout()
540
541 · live with it
542
543 · don't use XML::Simple
544
545 Why does XMLout() insert <name> elements (or attributes)?
546
547 Try setting keyattr => [].
548
549 When you call XMLin() to read XML, the 'keyattr' option controls
550 whether arrays get 'folded' into hashes. Similarly, when you call
551 XMLout(), the 'keyattr' option controls whether hashes get 'unfolded'
552 into arrays. As described above, 'keyattr' is enabled by default.
553
554 Why are empty elements represented as empty hashes?
555
556 An element is always represented as a hash unless it contains only
557 text, in which case it is represented as a scalar string.
558
559 If you would prefer empty elements to be represented as empty strings
560 or the undefined value, set the 'suppressempty' option to '' or undef
561 respectively.
562
563 Why is ParserOpts deprecated?
564
565 The "ParserOpts" option is a remnant of the time when XML::Simple only
566 worked with the XML::Parser API. Its value is completely ignored if
567 you're using a SAX parser, so writing code which relied on it would bar
568 you from taking advantage of SAX.
569
570 Even if you are using XML::Parser, it is seldom necessary to pass
571 options to the parser object. A number of people have written to say
572 they use this option to set XML::Parser's "ProtocolEncoding" option.
573 Don't do that, it's wrong, Wrong, WRONG! Fix the XML document so that
574 it's well-formed and you won't have a problem.
575
576 Having said all of that, as long as XML::Simple continues to support
577 the XML::Parser API, this option will not be removed. There are cur‐
578 rently no plans to remove support for the XML::Parser API.
579
580
581
582perl v5.8.8 2004-11-19 XML::Simple::FAQ(3)