home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / FAQ.pod < prev    next >
Encoding:
Text File  |  2002-10-12  |  18.7 KB  |  629 lines

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