Know-How für Ihr Projekt

Perl Documentation


XML::LibXML::Parser - Parsing XML Data with XML::LibXML


use XML::LibXML '1.70';
# Parser constructor
$parser = XML::LibXML->new();
$parser = XML::LibXML->new(option=>value, ...);
$parser = XML::LibXML->new({option=>value, ...});
# Parsing XML
$dom = XML::LibXML->load_xml(
    location => $file_or_url
    # parser options ...
$dom = XML::LibXML->load_xml(
    string => $xml_string
    # parser options ...
$dom = XML::LibXML->load_xml(
    string => (\$xml_string)
    # parser options ...
$dom = XML::LibXML->load_xml({
    IO => $perl_file_handle
    # parser options ...
$dom = $parser->load_xml(...);
# Parsing HTML
$dom = XML::LibXML->load_html(...);
$dom = $parser->load_html(...);
# Parsing well-balanced XML chunks
$fragment = $parser->parse_balanced_chunk( $wbxmlstring, $encoding );
# Processing XInclude
$parser->process_xincludes( $doc );
$parser->processXIncludes( $doc );
# Old-style parser interfaces
$doc = $parser->parse_file( $xmlfilename );
$doc = $parser->parse_fh( $io_fh );
$doc = $parser->parse_string( $xmlstring);
$doc = $parser->parse_html_file( $htmlfile, \%opts );
$doc = $parser->parse_html_fh( $io_fh, \%opts );
$doc = $parser->parse_html_string( $htmlstring, \%opts );
# Push parser
$parser->parse_chunk($string, $terminate);
$doc = $parser->finish_push( $recover );
# Set/query parser options
# XML catalogs
$parser->load_catalog( $catalog_file );


An XML document is read into a data structure such as a DOM tree by a piece of software, called a parser. XML::LibXML currently provides four different parser interfaces:

Creating a Parser Instance

XML::LibXML provides an OO interface to the libxml2 parser functions. Thus you have to create a parser instance before you can parse any XML data.

DOM Parser

One of the common parser interfaces of XML::LibXML is the DOM parser. This parser reads XML data into a DOM like data structure, so each tag can get accessed and transformed.

XML::LibXML's DOM parser is not only capable to parse XML data, but also (strict) HTML files. There are three ways to parse documents - as a string, as a Perl filehandle, or as a filename/URL. The return value from each is a XML::LibXML::Document object, which is a DOM object.

All of the functions listed below will throw an exception if the document is invalid. To prevent this causing your program exiting, wrap the call in an eval{} block

Parsing HTML may cause problems, especially if the ampersand ('&') is used. This is a common problem if HTML code is parsed that contains links to CGI-scripts. Such links cause the parser to throw errors. In such cases libxml2 still parses the entire document as there was no error, but the error causes XML::LibXML to stop the parsing process. However, the document is not lost. Such HTML documents should be parsed using the recover flag. By default recovering is deactivated.

The functions described above are implemented to parse well formed documents. In some cases a program gets well balanced XML instead of well formed documents (e.g. an XML fragment from a database). With XML::LibXML it is not required to wrap such fragments in the code, because XML::LibXML is capable even to parse well balanced XML fragments.

By default XML::LibXML does not process XInclude tags within an XML Document (see options section below). XML::LibXML allows one to post-process a document to expand XInclude tags.

Push Parser

XML::LibXML provides a push parser interface. Rather than pulling the data from a given source the push parser waits for the data to be pushed into it.

This allows one to parse large documents without waiting for the parser to finish. The interface is especially useful if a program needs to pre-process the incoming pieces of XML (e.g. to detect document boundaries).

While XML::LibXML parse_*() functions force the data to be a well-formed XML, the push parser will take any arbitrary string that contains some XML data. The only requirement is that all the pushed strings are together a well formed document. With the push parser interface a program can interrupt the parsing process as required, where the parse_*() functions give not enough flexibility.

Different to the pull parser implemented in parse_fh() or parse_file(), the push parser is not able to find out about the documents end itself. Thus the calling program needs to indicate explicitly when the parsing is done.

In XML::LibXML this is done by a single function:

Internally XML::LibXML provides three functions that control the push parser process:

Pull Parser (Reader)

XML::LibXML also provides a pull-parser interface similar to the XmlReader interface in .NET. This interface is almost streaming, and is usually faster and simpler to use than SAX. See XML::LibXML::Reader.

Direct SAX Parser

XML::LibXML provides a direct SAX parser in the XML::LibXML::SAX module.

DOM based SAX Parser

XML::LibXML also provides a DOM based SAX parser. The SAX parser is defined in the module XML::LibXML::SAX::Parser. As it is not a stream based parser, it parses documents into a DOM and traverses the DOM tree instead.

The API of this parser is exactly the same as any other Perl SAX2 parser. See XML::SAX::Intro for details.

Aside from the regular parsing methods, you can access the DOM tree traverser directly, using the generate() method:

my $doc = build_yourself_a_document();
my $saxparser = $XML::LibXML::SAX::Parser->new( ... );
$parser->generate( $doc );

This is useful for serializing DOM trees, for example that you might have done prior processing on, or that you have as a result of XSLT processing.


This is NOT a streaming SAX parser. As I said above, this parser reads the entire document into a DOM and serialises it. Some people couldn't read that in the paragraph above so I've added this warning. If you want a streaming SAX parser look at the XML::LibXML::SAX man page


XML::LibXML provides some functions to serialize nodes and documents. The serialization functions are described on the XML::LibXML::Node manpage or the XML::LibXML::Document manpage. XML::LibXML checks three global flags that alter the serialization process:

of that three functions only setTagCompression is available for all serialization functions.

Because XML::LibXML does these flags not itself, one has to define them locally as the following example shows:

local $XML::LibXML::skipXMLDeclaration = 1;
local $XML::LibXML::skipDTD = 1;
local $XML::LibXML::setTagCompression = 1;

If skipXMLDeclaration is defined and not '0', the XML declaration is omitted during serialization.

If skipDTD is defined and not '0', an existing DTD would not be serialized with the document.

If setTagCompression is defined and not '0' empty tags are displayed as open and closing tags rather than the shortcut. For example the empty tag foo will be rendered as <foo></foo> rather than <foo/>.


Handling of libxml2 parser options has been unified and improved in XML::LibXML 1.70. You can now set default options for a particular parser instance by passing them to the constructor as XML::LibXML->new({name=>value, ...}) or XML::LibXML->new(name=>value,...). The options can be queried and changed using the following methods (pre-1.70 interfaces such as $parser->load_ext_dtd(0) also exist, see below):

IMPORTANT NOTE: This documentation reflects the parser flags available in libxml2 2.7.3. Some options have no effect if an older version of libxml2 is used.

Each of the flags listed below is labeled

Unless specified otherwise, the default for boolean valued options is 0 (false).

The available options are:

For compatibility with XML::LibXML versions prior to 1.70, the following methods are also supported for querying and setting the corresponding parser options (if called without arguments, the methods return the current value of the corresponding parser options; with an argument sets the option to a given value):


The following obsolete methods trigger parser options in some special way:


libxml2 supports XML catalogs. Catalogs are used to map remote resources to their local copies. Using catalogs can speed up parsing processes if many external resources from remote addresses are loaded into the parsed documents (such as DTDs or XIncludes).

Note that libxml2 has a global pool of loaded catalogs, so if you apply the method load_catalog to one parser instance, all parser instances will start using the catalog (in addition to other previously loaded catalogs).

Note also that catalogs are not used when a custom external entity handler is specified. At the current state it is not possible to make use of both types of resolving systems at the same time.


XML::LibXML throws exceptions during parsing, validation or XPath processing (and some other occasions). These errors can be caught by using eval blocks. The error is stored in $@. There are two implementations: the old one throws $@ which is just a message string, in the new one $@ is an object from the class XML::LibXML::Error; this class overrides the operator "" so that when printed, the object flattens to the usual error message.

XML::LibXML throws errors as they occur. This is a very common misunderstanding in the use of XML::LibXML. If the eval is omitted, XML::LibXML will always halt your script by "croaking" (see Carp man page for details).

Also note that an increasing number of functions throw errors if bad data is passed as arguments. If you cannot assure valid data passed to XML::LibXML you should eval these functions.

Note: since version 1.59, get_last_error() is no longer available in XML::LibXML for thread-safety reasons.


Matt Sergeant, Christian Glahn, Petr Pajas




2001-2007, Ltd.

2002-2006, Christian Glahn.

2006-2009, Petr Pajas.


This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.