FAQ.pod 20 KB

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