Parse XML
In this tutorial you will learn how to parse some simple XML. We’ve provided an example XML file below. This is the file we used for all our testing, called test.xml.
XML::Simple
The Expat library, available from SourceForge, is commonly used to build and parse XML. The Perl mobulde XML::Parser (and related modules) is a very powerful modules for parsing XML in many different formats. However, because of the power of the module, the output can be difficult to follow. The XML::Simple module provides a simple interface to the output of this, and other, XML module.
The script below uses XML::Simple to read the XML from test.xml into a simple hash structure. We are using Data::Dumper to show you the output easily.
Using our test.xml this would produce the following output:
So if you wanted a script that printed how old everyone was, you could write:
Which would produce:
XML::Smart
More like XML::Difficult
XML::Parser::EasyTree
Easier than XML::Parser.
XML::Mini
This module provides a pure Perl XML parser. Unlink XML::Parser it does not require any external libraries or modules. The parse subroutine accepts a string of xml (not a filename), and the toHash function builds the xml into a hash structure much like that in XML::Simple.
The program below parses the example test.xml file and we use Data::Dumper to display the output:
The output of this program would be:
Note that attributes (i.e. name) are treated the same as children tags of a node. For example, if we added a tag called ‘name’ to the Melissa Person, the output of the above program would be: