{
    "mode": "perldoc",
    "parameter": "XML::Simple::FAQ",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/XML%3A%3ASimple%3A%3AFAQ/json",
    "generated": "2026-06-10T16:42:10Z",
    "sections": {
        "NAME": {
            "content": "XML::Simple::FAQ - Frequently Asked Questions about XML::Simple\n",
            "subsections": []
        },
        "Basics": {
            "content": "What should I use XML::Simple for?\nNothing!\n\nIt's as simple as that.\n\nChoose a better module. See Perl XML::LibXML by Example\n<http://grantm.github.io/perl-libxml-by-example/> for a gentle introduction to XML::LibXML with\nlots of examples.\n\nWhat was XML::Simple designed to be used for?\nXML::Simple is a Perl module that was originally developed as a tool for reading and writing\nconfiguration data in XML format. You could use it for other purposes that involve storing and\nretrieving structured data in XML but it's likely to be a frustrating experience.\n\nWhy store configuration data in XML anyway?\nIt seemed like a good idea at the time. Now, I use and recommend Config::General which uses a\nformat similar to that used by the Apache web server. This is easier to read than XML while\nstill allowing advanced concepts such as nested sections.\n\nAt the time XML::Simple was written, the advantages of using XML format for configuration data\nwere thought to include:\n\n*   Using existing XML parsing tools requires less development time, is easier and more robust\nthan developing your own config file parsing code\n\n*   XML can represent relationships between pieces of data, such as nesting of sections to\narbitrary levels (not easily done with .INI files for example)\n\n*   XML is basically just text, so you can easily edit a config file (easier than editing a\nWin32 registry)\n\n*   XML provides standard solutions for handling character sets and encoding beyond basic ASCII\n(important for internationalization)\n\n*   If it becomes necessary to change your configuration file format, there are many tools\navailable for performing transformations on XML files\n\n*   XML is an open standard (the world does not need more proprietary binary file formats)\n\n*   Taking the extra step of developing a DTD allows the format of configuration files to be\nvalidated before your program reads them (not directly supported by XML::Simple)\n\n*   Combining a DTD with a good XML editor can give you a GUI config editor for minimal coding\neffort\n\nWhat isn't XML::Simple good for?\nThe main limitation of XML::Simple is that it does not work with 'mixed content' (see the next\nquestion). If you consider your XML files contain marked up text rather than structured data,\nyou should probably use another module.\n\nIf your source XML documents change regularly, it's likely that you will experience intermittent\nfailures. In particular, failure to properly use the ForceArray and KeyAttr options will produce\ncode that works when you get a list of elements with the same name, but fails when there's only\none item in the list. These types of problems can be avoided by not using XML::Simple in the\nfirst place.\n\nIf you are working with very large XML files, XML::Simple's approach of representing the whole\nfile in memory as a 'tree' data structure may not be suitable.\n\nWhat is mixed content?\nConsider this example XML:\n\n<document>\n<para>This is <em>mixed</em> content.</para>\n</document>\n\nThis is said to be mixed content, because the <para> element contains both character data (text\ncontent) and nested elements.\n\nHere's some more XML:\n\n<person>\n<firstname>Joe</firstname>\n<lastname>Bloggs</lastname>\n<dob>25-April-1969</dob>\n</person>\n\nThis second example is not generally considered to be mixed content. The <firstname>,\n<lastname> and <dob> elements contain only character data and the <person> element contains\nonly nested elements. (Note: Strictly speaking, the whitespace between the nested elements is\ncharacter data, but it is ignored by XML::Simple).\n\nWhy doesn't XML::Simple handle mixed content?\nBecause if it did, it would no longer be simple :-)\n\nSeriously though, there are plenty of excellent modules that allow you to work with mixed\ncontent in a variety of ways. Handling mixed content correctly is not easy and by ignoring these\nissues, XML::Simple is able to present an API without a steep learning curve.\n\nWhich Perl modules do handle mixed content?\nEvery one of them except XML::Simple :-)\n\nIf you're looking for a recommendation, I'd suggest you look at the Perl-XML FAQ at:\n\nhttp://perl-xml.sourceforge.net/faq/\n",
            "subsections": []
        },
        "Installation": {
            "content": "How do I install XML::Simple?\nIf you're running ActiveState Perl, or Strawberry Perl <http://strawberryperl.com/> you've\nprobably already got XML::Simple and therefore do not need to install it at all. But you\nprobably also have XML::LibXML, which is a much better module, so just use that.\n\nIf you do need to install XML::Simple, you'll need to install an XML parser module first.\nInstall either XML::Parser (which you may have already) or XML::SAX. If you install both,\nXML::SAX will be used by default.\n\nOnce you have a parser installed ...\n\nOn Unix systems, try:\n\nperl -MCPAN -e 'install XML::Simple'\n\nIf that doesn't work, download the latest distribution from\nftp://ftp.cpan.org/pub/CPAN/authors/id/G/GR/GRANTM , unpack it and run these commands:\n\nperl Makefile.PL\nmake\nmake test\nmake install\n\nOn Win32, if you have a recent build of ActiveState Perl (618 or better) try this command:\n\nppm install XML::Simple\n\nIf that doesn't work, you really only need the Simple.pm file, so extract it from the .tar.gz\nfile (eg: using WinZIP) and save it in the \\site\\lib\\XML directory under your Perl installation\n(typically C:\\Perl).\n\nI'm trying to install XML::Simple and 'make test' fails\nIs the directory where you've unpacked XML::Simple mounted from a file server using NFS, SMB or\nsome other network file sharing? If so, that may cause errors in the following test scripts:\n\n3Storable.t\n4MemShare.t\n5MemCopy.t\n\nThe test suite is designed to exercise the boundary conditions of all XML::Simple's\nfunctionality and these three scripts exercise the caching functions. If XML::Simple is asked to\nparse a file for which it has a cached copy of a previous parse, then it compares the timestamp\non the XML file with the timestamp on the cached copy. If the cached copy is *newer* then it\nwill be used. If the cached copy is older or the same age then the file is re-parsed. The test\nscripts will get confused by networked filesystems if the workstation and server system clocks\nare not synchronised (to the second).\n\nIf you get an error in one of these three test scripts but you don't plan to use the caching\noptions (they're not enabled by default), then go right ahead and run 'make install'. If you do\nplan to use caching, then try unpacking the distribution on local disk and doing the build/test\nthere.\n\nIt's probably not a good idea to use the caching options with networked filesystems in\nproduction. If the file server's clock is ahead of the local clock, XML::Simple will re-parse\nfiles when it could have used the cached copy. However if the local clock is ahead of the file\nserver clock and a file is changed immediately after it is cached, the old cached copy will be\nused.\n\nIs one of the three test scripts (above) failing but you're not running on a network filesystem?\nAre you running Win32? If so, you may be seeing a bug in Win32 where writes to a file do not\naffect its modification timestamp.\n\nIf none of these scenarios match your situation, please confirm you're running the latest\nversion of XML::Simple and then email the output of 'make test' to me at grantm@cpan.org\n\nWhy is XML::Simple so slow?\nIf you find that XML::Simple is very slow reading XML, the most likely reason is that you have\nXML::SAX installed but no additional SAX parser module. The XML::SAX distribution includes an\nXML parser written entirely in Perl. This is very portable but not very fast. For better\nperformance install either XML::SAX::Expat or XML::LibXML.\n",
            "subsections": []
        },
        "Usage": {
            "content": "How do I use XML::Simple?\nIf you don't know how to use XML::Simple then the best approach is to learn to use XML::LibXML\n<http://grantm.github.io/perl-libxml-by-example/> instead. Stop reading this document and use\nthat one instead.\n\nIf you are determined to use XML::Simple, it come with copious documentation, so read that.\n\nThere are so many options, which ones do I really need to know about?\nAlthough you can get by without using any options, you shouldn't even consider using XML::Simple\nin production until you know what these two options do:\n\n*   forcearray\n\n*   keyattr\n\nThe reason you really need to read about them is because the default values for these options\nwill trip you up if you don't. Although everyone agrees that these defaults are not ideal, there\nis not wide agreement on what they should be changed to. The answer therefore is to read about\nthem (see below) and select values which are right for you.\n\nWhat is the forcearray option all about?\nConsider this XML in a file called ./person.xml:\n\n<person>\n<firstname>Joe</firstname>\n<lastname>Bloggs</lastname>\n<hobbie>bungy jumping</hobbie>\n<hobbie>sky diving</hobbie>\n<hobbie>knitting</hobbie>\n</person>\n\nYou could read it in with this line:\n\nmy $person = XMLin('./person.xml');\n\nWhich would give you a data structure like this:\n\n$person = {\n'firstname' => 'Joe',\n'lastname'  => 'Bloggs',\n'hobbie'     => [ 'bungy jumping', 'sky diving', 'knitting' ]\n};\n\nThe <firstname> and <lastname> elements are represented as simple scalar values which you\ncould refer to like this:\n\nprint \"$person->{firstname} $person->{lastname}\\n\";\n\nThe <hobbie> elements are represented as an array - since there is more than one. You could\nrefer to the first one like this:\n\nprint $person->{hobbie}->[0], \"\\n\";\n\nOr the whole lot like this:\n\nprint join(', ', @{$person->{hobbie}} ), \"\\n\";\n\nThe catch is, that these last two lines of code will only work for people who have more than one\nhobbie. If there is only one <hobbie> element, it will be represented as a simple scalar (just\nlike <firstname> and <lastname>). Which might lead you to write code like this:\n\nif(ref($person->{hobbie})) {\nprint join(', ', @{$person->{hobbie}} ), \"\\n\";\n}\nelse {\nprint $person->{hobbie}, \"\\n\";\n}\n\nDon't do that.\n\nOne alternative approach is to set the forcearray option to a true value:\n\nmy $person = XMLin('./person.xml', forcearray => 1);\n\nWhich will give you a data structure like this:\n\n$person = {\n'firstname' => [ 'Joe' ],\n'lastname'  => [ 'Bloggs' ],\n'hobbie'     => [ 'bungy jumping', 'sky diving', 'knitting' ]\n};\n\nThen you can use this line to refer to all the list of hobbies even if there was only one:\n\nprint join(', ', @{$person->{hobbie}} ), \"\\n\";\n\nThe downside of this approach is that the <firstname> and <lastname> elements will also always\nbe represented as arrays even though there will never be more than one:\n\nprint \"$person->{firstname}->[0] $person->{lastname}->[0]\\n\";\n\nThis might be OK if you change the XML to use attributes for things that will always be singular\nand nested elements for things that may be plural:\n\n<person firstname=\"Jane\" lastname=\"Bloggs\">\n<hobbie>motorcycle maintenance</hobbie>\n</person>\n\nOn the other hand, if you prefer not to use attributes, then you could specify that any <hobbie>\nelements should always be represented as arrays and all other nested elements should be simple\nscalar values unless there is more than one:\n\nmy $person = XMLin('./person.xml', forcearray => [ 'hobbie' ]);\n\nThe forcearray option accepts a list of element names which should always be forced to an array\nrepresentation:\n\nforcearray => [ qw(hobbie qualification childsname) ]\n\nSee the XML::Simple manual page for more information.\n\nWhat is the keyattr option all about?\nConsider this sample XML:\n\n<catalog>\n<part partnum=\"1842334\" desc=\"High pressure flange\" price=\"24.50\" />\n<part partnum=\"9344675\" desc=\"Threaded gasket\"      price=\"9.25\" />\n<part partnum=\"5634896\" desc=\"Low voltage washer\"   price=\"12.00\" />\n</catalog>\n\nYou could slurp it in with this code:\n\nmy $catalog = XMLin('./catalog.xml');\n\nWhich would return a data structure like this:\n\n$catalog = {\n'part' => [\n{\n'partnum' => '1842334',\n'desc'    => 'High pressure flange',\n'price'   => '24.50'\n},\n{\n'partnum' => '9344675',\n'desc'    => 'Threaded gasket',\n'price'   => '9.25'\n},\n{\n'partnum' => '5634896',\n'desc'    => 'Low voltage washer',\n'price'   => '12.00'\n}\n]\n};\n\nThen you could access the description of the first part in the catalog with this code:\n\nprint $catalog->{part}->[0]->{desc}, \"\\n\";\n\nHowever, if you wanted to access the description of the part with the part number of \"9344675\"\nthen you'd have to code a loop like this:\n\nforeach my $part (@{$catalog->{part}}) {\nif($part->{partnum} eq '9344675') {\nprint $part->{desc}, \"\\n\";\nlast;\n}\n}\n\nThe knowledge that each <part> element has a unique partnum attribute allows you to eliminate\nthis search. You can pass this knowledge on to XML::Simple like this:\n\nmy $catalog = XMLin($xml, keyattr => ['partnum']);\n\nWhich will return a data structure like this:\n\n$catalog = {\n'part' => {\n'5634896' => { 'desc' => 'Low voltage washer',   'price' => '12.00' },\n'1842334' => { 'desc' => 'High pressure flange', 'price' => '24.50' },\n'9344675' => { 'desc' => 'Threaded gasket',      'price' => '9.25'  }\n}\n};\n\nXML::Simple has been able to transform $catalog->{part} from an arrayref to a hashref (keyed on\npartnum). This transformation is called 'array folding'.\n\nThrough the use of array folding, you can now index directly to the description of the part you\nwant:\n\nprint $catalog->{part}->{9344675}->{desc}, \"\\n\";\n\nThe 'keyattr' option also enables array folding when the unique key is in a nested element\nrather than an attribute. eg:\n\n<catalog>\n<part>\n<partnum>1842334</partnum>\n<desc>High pressure flange</desc>\n<price>24.50</price>\n</part>\n<part>\n<partnum>9344675</partnum>\n<desc>Threaded gasket</desc>\n<price>9.25</price>\n</part>\n<part>\n<partnum>5634896</partnum>\n<desc>Low voltage washer</desc>\n<price>12.00</price>\n</part>\n</catalog>\n\nSee the XML::Simple manual page for more information.\n\nSo what's the catch with 'keyattr'?\nOne thing to watch out for is that you might get array folding even if you don't supply the\nkeyattr option. The default value for this option is:\n\n[ 'name', 'key', 'id']\n\nWhich means if your XML elements have a 'name', 'key' or 'id' attribute (or nested element) then\nthey may get folded on those values. This means that you can take advantage of array folding\nsimply through careful choice of attribute names. On the hand, if you really don't want array\nfolding at all, you'll need to set 'key attr to an empty list:\n\nmy $ref = XMLin($xml, keyattr => []);\n\nA second 'gotcha' is that array folding only works on arrays. That might seem obvious, but if\nthere's only one record in your XML and you didn't set the 'forcearray' option then it won't be\nrepresented as an array and consequently won't get folded into a hash. The moral is that if\nyou're using array folding, you should always turn on the forcearray option.\n\nYou probably want to be as specific as you can be too. For instance, the safest way to parse the\n<catalog> example above would be:\n\nmy $catalog = XMLin($xml, keyattr => { part => 'partnum'},\nforcearray => ['part']);\n\nBy using the hashref for keyattr, you can specify that only <part> elements should be folded on\nthe 'partnum' attribute (and that the <part> elements should not be folded on any other\nattribute).\n\nBy supplying a list of element names for forcearray, you're ensuring that folding will work even\nif there's only one <part>. You're also ensuring that if the 'partnum' unique key is supplied in\na nested element then that element won't get forced to an array too.\n\nHow do I know what my data structure should look like?\nThe rules are fairly straightforward:\n\n*   each element gets represented as a hash\n\n*   unless it contains only text, in which case it'll be a simple scalar value\n\n*   or unless there's more than one element with the same name, in which case they'll be\nrepresented as an array\n\n*   unless you've got array folding enabled, in which case they'll be folded into a hash\n\n*   empty elements (no text contents and no attributes) will either be represented as an empty\nhash, an empty string or undef - depending on the value of the 'suppressempty' option.\n\nIf you're in any doubt, use Data::Dumper, eg:\n\nuse XML::Simple;\nuse Data::Dumper;\n\nmy $ref = XMLin($xml);\n\nprint Dumper($ref);\n\nI'm getting 'Use of uninitialized value' warnings\nYou're probably trying to index into a non-existant hash key - try Data::Dumper.\n\nI'm getting a 'Not an ARRAY reference' error\nSomething that you expect to be an array is not. The two most likely causes are that you forgot\nto use 'forcearray' or that the array got folded into a hash - try Data::Dumper.\n\nI'm getting a 'No such array field' error\nSomething that you expect to be a hash is actually an array. Perhaps array folding failed\nbecause one element was missing the key attribute - try Data::Dumper.\n\nI'm getting an 'Out of memory' error\nSomething in the data structure is not as you expect and Perl may be trying unsuccessfully to\nautovivify things - try Data::Dumper.\n\nIf you're already using Data::Dumper, try calling Dumper() immediately after XMLin() - ie:\nbefore you attempt to access anything in the data structure.\n",
            "subsections": [
                {
                    "name": "My element order is getting jumbled up",
                    "content": "If you read an XML file with XMLin() and then write it back out with XMLout(), the order of the\nelements will likely be different. (However, if you read the file back in with XMLin() you'll\nget the same Perl data structure).\n\nThe reordering happens because XML::Simple uses hashrefs to store your data and Perl hashes do\nnot really have any order.\n\nIt is possible that a future version of XML::Simple will use Tie::IxHash to store the data in\nhashrefs which do retain the order. However this will not fix all cases of element order being\nlost.\n\nIf your application really is sensitive to element order, don't use XML::Simple (and don't put\norder-sensitive values in attributes).\n\nXML::Simple turns nested elements into attributes\nIf you read an XML file with XMLin() and then write it back out with XMLout(), some data which\nwas originally stored in nested elements may end up in attributes. (However, if you read the\nfile back in with XMLin() you'll get the same Perl data structure).\n\nThere are a number of ways you might handle this:\n\n*   use the 'forcearray' option with XMLin()\n\n*   use the 'noattr' option with XMLout()\n\n*   live with it\n\n*   don't use XML::Simple\n\nWhy does XMLout() insert <name> elements (or attributes)?\nTry setting keyattr => [].\n\nWhen you call XMLin() to read XML, the 'keyattr' option controls whether arrays get 'folded'\ninto hashes. Similarly, when you call XMLout(), the 'keyattr' option controls whether hashes get\n'unfolded' into arrays. As described above, 'keyattr' is enabled by default.\n\nWhy are empty elements represented as empty hashes?\nAn element is always represented as a hash unless it contains only text, in which case it is\nrepresented as a scalar string.\n\nIf you would prefer empty elements to be represented as empty strings or the undefined value,\nset the 'suppressempty' option to '' or undef respectively.\n\nWhy is ParserOpts deprecated?\nThe \"ParserOpts\" option is a remnant of the time when XML::Simple only worked with the\nXML::Parser API. Its value is completely ignored if you're using a SAX parser, so writing code\nwhich relied on it would bar you from taking advantage of SAX.\n\nEven if you are using XML::Parser, it is seldom necessary to pass options to the parser object.\nA number of people have written to say they use this option to set XML::Parser's\n\"ProtocolEncoding\" option. Don't do that, it's wrong, Wrong, WRONG! Fix the XML document so that\nit's well-formed and you won't have a problem.\n\nHaving said all of that, as long as XML::Simple continues to support the XML::Parser API, this\noption will not be removed. There are currently no plans to remove support for the XML::Parser\nAPI.\n"
                }
            ]
        }
    },
    "summary": "XML::Simple::FAQ - Frequently Asked Questions about XML::Simple",
    "flags": [],
    "examples": [],
    "see_also": []
}