XML::Li...::Parser(3)

πŸ’– NAME πŸ’–

XML::LibXML::Parser β€” Parsing XML Data with XML::LibXML

okay so you found the manual page bestie, and yes, it's the page β€” this is XML::LibXML::Parser(3) from the User Contributed Perl Documentation, and it's literally all about pulling XML data into XML::LibXML. sit down, grab a strawberry, we're doing this πŸ“


✨ SYNOPSIS ✨

here's the whole vibe at a glance, no cap:

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);
$parser->init_push();
$parser->push(@data);
$doc = $parser->finish_push( $recover );

# Set/query parser options

$parser->option_exists($name);
$parser->get_option($name);
$parser->set_option($name,$value);
$parser->set_options({$name=>$value,...});

# XML catalogs

$parser->load_catalog( $catalog_file );

like, that's the whole menu πŸ’… every single one of these gets its own little moment later on, don't worry.


πŸ”₯ PARSING πŸ”₯

so here's the tea πŸ«– β€” when you read an XML document into a data structure (think: a DOM tree), the software doing that job is called a parser. and XML::LibXML? she's generous. she currently hands you four different parser interfaces:

  • A DOM Pull-Parser
  • A DOM Push-Parser
  • A SAX Parser
  • A DOM based SAX Parser.

four options, all valid, all iconic πŸ‘‘


πŸŽ€ Creating a Parser Instance πŸŽ€

XML::LibXML gives you an OO interface to the libxml2 parser functions. so bestie, before you can parse literally any XML data, you gotta make yourself a parser instance first. no parser, no parsing, that's just how it is πŸ™ˆ

new

$parser = XML::LibXML->new();
$parser = XML::LibXML->new(option=>value, ...);
$parser = XML::LibXML->new({option=>value, ...});

this makes you a brand new XML and HTML parser instance ✨ each parser instance carries around its own default values for all the various parser options. and if you want, you can hand it either a hash reference or a list of option => value pairs to set yourself a different default set of options. customisation, we love her πŸ’…

unless it says otherwise, the options load_ext_dtd and expand_entities are set to 1. and if you wanna see the full list of libxml2 parser options, go peek at "Parser Options".


πŸ’… DOM Parser πŸ’…

one of the common parser interfaces of XML::LibXML is the DOM parser. this one reads your XML data into a DOM-like data structure, so every single tag can be accessed and transformed. main character behaviour, honestly.

XML::LibXML's DOM parser isn't just about XML, btw β€” she can also parse (strict) HTML files πŸŽ€ and there are three ways to parse a document: as a string, as a Perl filehandle, or as a filename/URL. every single one of them hands you back an XML::LibXML::Document object, which is a DOM object.

⚠️ heads up bestie β€” all the functions down below will throw an exception if the document is invalid. and if you don't wanna watch your program just exit on you like that πŸ’€ wrap the call in an eval{} block. protect your peace.

load_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(...);

this one's been around since XML::LibXML 1.70, and she's the easy-to-use interface to the XML parser β€” she takes a given file (or non-HTTPS URL), a string, or an input stream and turns it into a DOM tree 🌈

you can pass your arguments in a HASH reference or as name => value pairs. and you can call her as a class method or an object method. in both cases she internally creates a new parser instance and passes along the parser options you specified. if you called her as an object method, she clones the original parser (keeping all its settings, queen) and then additionally applies the specified options to the new parser. more info over in the constructor new and "Parser Options".

🚨 okay important: because of a limitation in the underlying libxml2 library, this call does not recognize HTTPS-based URLs. it will straight up treat an HTTPS URL as a filename, which likely means it throws a No such file or directory exception. rude, but that's the reality πŸ™ˆ

load_html

$dom = XML::LibXML->load_html(...);
$dom = $parser->load_html(...);

available since XML::LibXML 1.70 too ✨ same usage as load_xml, except she's the interface to the HTML parser. go read "load_xml" if you want the full story.

okay so β€” parsing HTML can cause problems, especially if the ampersand ('&') shows up. this is a super common issue when the HTML you're parsing has links to CGI-scripts in it. links like that make the parser throw errors 😭 and here's the messy part: in those cases libxml2 still parses the entire document like there was no error at all β€” but the error makes XML::LibXML stop the parsing process. good news? the document isn't lost. documents like this should be parsed using the recover flag. and by default? recovering is deactivated. so turn it on if you need it.

so the functions we just described are built to parse well formed documents. but sometimes your program gets well balanced XML instead of well formed documents β€” like, say, an XML fragment from a database 🫠 with XML::LibXML you don't have to wrap those fragments in the code, because she can parse well balanced XML fragments too. versatile icon.

parse_balanced_chunk

$fragment = $parser->parse_balanced_chunk( $wbxmlstring, $encoding );

this one parses a well balanced XML string into an XML::LibXML::DocumentFragment πŸ’– the first argument is your input string, and the optional second argument lets you specify the character encoding of the input (UTF-8 is what's assumed by default).

parse_xml_chunk

this is the old name of parse_balanced_chunk(). and because it can cause confusion with the push parser interface, this function should not be used anymore. we're retiring her, respectfully πŸ’€


by default, XML::LibXML does not process XInclude tags inside an XML Document (check the options section below for that). but XML::LibXML does let you post-process a document to expand those XInclude tags. slay.

process_xincludes

$parser->process_xincludes( $doc );

once a document has been parsed into a DOM structure, you might wanna expand the document's XInclude tags. this function processes the given document structure and expands all the XInclude tags (or throws an error) using the flags and callbacks of the given parser instance ✨

note that after successfully processing the document, the resulting Tree contains some extra nodes (of type XML_XINCLUDE_START and XML_XINCLUDE_END). these nodes show where data was included into the original tree. and if the document gets serialized, these extra nodes will not show up πŸ‘€

⚠️ remember bestie: a Document with processed XIncludes differs from the original document after serialization, because the original XInclude tags will not get restored! it's giving permanent, no take-backs.

if the parser flag expand_xincludes is set to 1, you don't need to post-process the parsed document at all. convenient.

processXIncludes

$parser->processXIncludes( $doc );

this is just an alias to process_xincludes, except with a JAVA-like function name. same girl, different font πŸ’…

parse_file

$doc = $parser->parse_file( $xmlfilename );

this function parses an XML document from a file or the network. $xmlfilename can be either a filename or a (non-HTTPS) URL. and real talk: for parsing files, this function is the fastest choice β€” about 6-8 times faster than parse_fh(). speed demon πŸ”₯

parse_fh

$doc = $parser->parse_fh( $io_fh );

parse_fh() parses an IOREF or a subclass of IO::Handle.

because the data comes from an open handle, libxml2's parser doesn't know about the base URI of the document. so to set the base URI, you should use parse_fh() like this:

my $doc = $parser->parse_fh( $io_fh, $baseuri );

parse_string

$doc = $parser->parse_string( $xmlstring);

this function is similar to parse_fh(), but she parses an XML document that's available as a single string in memory β€” or, alternatively, as a reference to a scalar containing a string. and again, you can pass an optional base URI to the function 🫢

my $doc = $parser->parse_string( $xmlstring, $baseuri );
my $doc = $parser->parse_string(\$xmlstring, $baseuri);

parse_html_file

$doc = $parser->parse_html_file( $htmlfile, \%opts );

similar to parse_file() but she parses HTML (strict) documents. $htmlfile can be a filename or a (non-HTTPS) URL.

an optional second argument lets you pass some options to the HTML parser as a HASH reference. check the options labeled with HTML over in "Parser Options" 🌸

parse_html_fh

$doc = $parser->parse_html_fh( $io_fh, \%opts );

similar to parse_fh() but she parses HTML (strict) streams.

an optional second argument lets you pass some options to the HTML parser as a HASH reference. check the options labeled with HTML over in "Parser Options".

πŸ’€ note: the encoding option may not work correctly with this function in libxml2 < 2.6.27 if the HTML file declares charset using a META tag. old libxml2 energy, we don't love it.

parse_html_string

$doc = $parser->parse_html_string( $htmlstring, \%opts );

similar to parse_string() but she parses HTML (strict) strings.

an optional second argument lets you pass some options to the HTML parser as a HASH reference. check the options labeled with HTML over in "Parser Options" ✨


🫢 Push Parser 🫢

XML::LibXML provides a push parser interface, and the whole concept is so fun actually β€” instead of pulling the data from a given source, the push parser just sits there and waits for the data to be pushed into it. patient queen πŸ’…

this lets you parse large documents without waiting around for the parser to finish. and the interface is especially useful if your program needs to pre-process the incoming pieces of XML β€” like, to detect document boundaries πŸ‘€

Okay so here's the thing β€” the parse_*() functions are kinda ✨demanding✨: they force your data to already be a well-formed XML document before they'll even look at it. The push parser could never. It'll happily chew on any arbitrary string that's got some XML-ish data in it. The only rule? All the strings you push, together, have to add up to one well-formed document. No cap. πŸ’…

The vibe here is control: with the push parser your program can pause the parsing whenever it wants, and the parse_*() functions just don't give you that flexibility. Sorry bestie.

And heads up β€” unlike the pull parser that lives inside parse_fh() or parse_file(), the push parser is lowkey clueless about where the document ends. It can't figure that out on its own. So you have to tell it, explicitly, when you're done. 🫢

In XML::LibXML that whole "we're done here" moment is handled by one single function:


parse_chunk ✨

$parser->parse_chunk($string, $terminate);

parse_chunk() tries to parse a chunk of data β€” and no, it doesn't have to be well balanced, we're not judging. 😌 It takes two parameters: the chunk of data as a string, and optionally a termination flag. If that termination flag is set to a true value (like 1, iconic), parsing stops and the resulting document gets returned, exactly like this:

my $parser = XML::LibXML->new;
for my $string ( "<", "foo", ' bar="hello world"', "/>") {
     $parser->parse_chunk( $string );
}
my $doc = $parser->parse_chunk("", 1); # terminate the parsing

Internally, XML::LibXML ships three functions that run the whole push-parser operation, and they're the real main characters:

init_push πŸŽ€

$parser->init_push();

Initializes the push parser. That's it, that's the whole job. ✨

push πŸ¦‹

$parser->push(@data);

This one pushes the data stored inside the array over to libxml2's parser. And important: every single entry in @data must be a normal scalar! You can call this method over and over, repeatedly, as many times as you want. πŸ”

finish_push 🌸

$doc = $parser->finish_push( $recover );

This function returns the result of the parsing process. If you call it with no parameter at all, it will complain about non well-formed documents β€” like, full drama. πŸ’€ But if $restore is 1, the push parser can be used to restore broken or non well formed (XML) documents, as the following example shows:

eval {
    $parser->push( "<foo>", "bar" );
    $doc = $parser->finish_push();    # will report broken XML
};
if ( $@ ) {
   # ...
}

Now, that can get annoying if the closing tag got missed by accident. The following code will restore the document instead:

eval {
    $parser->push( "<foo>", "bar" );
    $doc = $parser->finish_push(1);   # will return the data parsed
                                      # unless an error happened
};

print $doc->toString(); # returns "<foo>bar</foo>"

And of course β€” finish_push() will return nothing if there was no data pushed to the parser before. Empty in, empty out, that's the deal. πŸ™ˆ


Pull Parser (Reader) πŸ“–

XML::LibXML also serves up a pull-parser interface, similar to the XmlReader interface in .NET. This one is almost streaming, and it's usually faster and simpler to use than SAX. Go check out XML::LibXML::Reader. ✨

Direct SAX Parser 🎷

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

DOM based SAX Parser 🌳

XML::LibXML also provides a DOM based SAX parser. That one is defined in the module XML::LibXML::SAX::Parser. And because it is not a stream based parser, it parses documents into a DOM and then traverses the DOM tree instead. Different technique, same energy.

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, one you might have done prior processing on, or one you have as a result of XSLT processing. 🫢

🚨 WARNING 🚨

This is NOT a streaming SAX parser. Like I said up there ⬆️, this parser reads the entire document into a DOM and serialises it. Some people apparently couldn't read that in the paragraph above, so boom, here's a whole warning about it. πŸ’€ If you want a streaming SAX parser, look at the XML::LibXML::SAX man page.


🌈 SERIALIZATION 🌈

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

  • skipXMLDeclaration
  • skipDTD
  • setTagCompression

And out of those three functions, only setTagCompression is available for all serialization functions. πŸ‘€

Because XML::LibXML does not set these flags itself, you have to define them locally, like this:

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/>. πŸ’…

πŸ’… PARSER OPTIONS ✨

okay bestie, so the whole libxml2 parser-options situation got a glow-up in XML::LibXML 1.70 πŸŽ€ and it's honestly so much cleaner now. You can set default options for a specific parser instance by handing them to the constructor like this:

XML::LibXML->new({name=>value, ...})

or like this:

XML::LibXML->new(name=>value,...)

and then you can peek at them and change them whenever with the methods below (the pre-1.70 interfaces are still kicking around too, like $parser->load_ext_dtd(0), scroll down for those 🫢):


🌸 option_exists

$parser->option_exists($name);

Returns 1 if your current XML::LibXML version supports the option $name, otherwise returns 0 πŸ’– (heads up tho: this does not necessarily mean the option is supported by the underlying libxml2 library, iykyk).

🌸 get_option

$parser->get_option($name);

Returns the current value of the parser option $name. Simple as that ✨

🌸 set_option

$parser->set_option($name,$value);

Sets option $name to value $value. slay πŸ’…

🌸 set_options

$parser->set_options({$name=>$value,...});

Sets multiple parsing options at once β€” the group-chat move, everything in one message πŸ“²


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. no cap, check your version bestie 😭

Each of the flags listed below is labeled:

  • /parser/ β€” if it can be used with a XML::LibXML parser object (i.e. passed to XML::LibXML->new, XML::LibXML->set_option, etc.)
  • /html/ β€” if it can be used passed to the parse_html_* methods
  • /reader/ β€” if it can be used with the XML::LibXML::Reader.

Unless specified otherwise, the default for boolean valued options is 0 (false). periodt πŸ’―

The available options are:


πŸ‘‘ URI

/parser, html, reader/

In case of parsing strings or file handles, XML::LibXML doesn't know about the base uri of the document. To make relative references such as XIncludes work, one has to set a base URI, that is then used for the parsed document. πŸ¦‹

πŸ‘‘ line_numbers

/parser, html, reader/

If this option is activated, libxml2 will store the line number of each element node in the parsed document. The line number can be obtained using the line_number() method of the XML::LibXML::Node class (for non-element nodes this may report the line number of the containing element). The line numbers are also used for reporting positions of validation errors. ⭐

IMPORTANT: due to limitations in the libxml2 library line numbers greater than 65535 will be returned as 65535. Unfortunately, this is a long and sad story 😭, please see <http://bugzilla.gnome.org/show_bug.cgi?id=325533> for more details.

πŸ‘‘ encoding

/html/

character encoding of the input 🌈

πŸ‘‘ recover

/parser, html, reader/

recover from errors; possible values are 0, 1, and 2

A true value turns on recovery mode which allows one to parse broken XML or HTML data. The recovery mode allows the parser to return the successfully parsed portion of the input document. This is useful for almost well-formed documents, where for example a closing tag is missing somewhere. Still, XML::LibXML will only parse until the first fatal (non-recoverable) error occurs, reporting recoverable parsing errors as warnings. To suppress even these warnings, use recover=>2. πŸ™ˆ

Note that validation is switched off automatically in recovery mode. πŸ’…

πŸ‘‘ expand_entities

/parser, reader/

substitute entities; possible values are 0 and 1; default is 1

Note that although this flag disables entity substitution, it does not prevent the parser from loading external entities; when substitution of an external entity is disabled, the entity will be represented in the document tree by an XML_ENTITY_REF_NODE node whose subtree will be the content obtained by parsing the external resource; Although this nesting is visible from the DOM it is transparent to XPath data model, so it is possible to match nodes in an unexpanded entity by the same XPath expression as if the entity were expanded. See also ext_ent_handler. 🧚

πŸ‘‘ ext_ent_handler

/parser/

Provide a custom external entity handler to be used when expand_entities is set to 1. Possible value is a subroutine reference.

This feature does not work properly in libxml2 < 2.6.27! πŸ’€

The subroutine provided is called whenever the parser needs to retrieve the content of an external entity. It is called with two arguments: the system ID (URI) and the public ID. The value returned by the subroutine is parsed as the content of the entity. ✨

This method can be used to completely disable entity loading, e.g. to prevent exploits of the type described at (<http://searchsecuritychannel.techtarget.com/generic/0,295582,sid97_gci1304703,00.html>), where a service is tricked to expose its private data by letting it parse a remote file (RSS feed) that contains an entity reference to a local file (e.g. /etc/fstab). 😭 stay safe out there bestie.

A more granular solution to this problem, however, is provided by custom URL resolvers, as in:

my $c = XML::LibXML::InputCallback->new();
sub match {   # accept file:/ URIs except for XML catalogs in /etc/xml/
  my ($uri) = @_;
  return ($uri=~m{^file:/}
          and $uri !~ m{^file:///etc/xml/})
         ? 1 : 0;
}
$c->register_callbacks([ \&match, sub{}, sub{}, sub{} ]);
$parser->input_callbacks($c);

πŸ‘‘ load_ext_dtd

/parser, reader/

load the external DTD subset while parsing; possible values are 0 and 1. Unless specified, XML::LibXML sets this option to 1. πŸ’–

This flag is also required for DTD Validation, to provide complete attribute, and to expand entities, regardless if the document has an internal subset. Thus switching off external DTD loading, will disable entity expansion, validation, and complete attributes on internal subsets as well. 🫢

πŸ‘‘ complete_attributes

/parser, reader/

create default DTD attributes; possible values are 0 and 1 ✨

πŸ‘‘ validation

/parser, reader/

validate with the DTD; possible values are 0 and 1 πŸ‘‘

πŸ‘‘ suppress_errors

/parser, html, reader/

suppress error reports; possible values are 0 and 1 🀫

πŸ‘‘ suppress_warnings

/parser, html, reader/

suppress warning reports; possible values are 0 and 1 🀫

πŸ‘‘ pedantic_parser

/parser, html, reader/

pedantic error reporting; possible values are 0 and 1 🧐

πŸ‘‘ no_blanks

/parser, html, reader/

remove blank nodes; possible values are 0 and 1 🧹

πŸ‘‘ no_defdtd

/html/

do not add a default DOCTYPE; possible values are 0 and 1

the default is (0) to add a DTD when the input html lacks one πŸŽ€

πŸ‘‘ expand_xinclude or xinclude

/parser, reader/

Implement XInclude substitution; possible values are 0 and 1 πŸ¦‹

Expands XInclude tags immediately while parsing the document. Note that the parser will use the URI resolvers installed via XML::LibXML::InputCallback to parse the included document (if any). πŸ’…

πŸ‘‘ no_xinclude_nodes

/parser, reader/

do not generate XINCLUDE START/END nodes; possible values are 0 and 1 🚫

πŸ‘‘ no_network

/parser, html, reader/

Forbid network access; possible values are 0 and 1 🌐

If set to true, all attempts to fetch non-local resources (such as DTD or external entities) will fail (unless custom callbacks are defined). 😭

It may be necessary to use the flag recover for processing documents requiring such resources while networking is off.

πŸ‘‘ clean_namespaces

/parser, reader/

remove redundant namespaces declarations during parsing; possible values are 0 and 1. 🧼

πŸ‘‘ no_cdata

/parser, html, reader/

merge CDATA as text nodes; possible values are 0 and 1 ✨

πŸ‘‘ no_basefix

/parser, reader/

not fixup XINCLUDE xml#base URIS; possible values are 0 and 1 πŸŽ€

πŸ‘‘ huge

/parser, html, reader/

relax any hardcoded limit from the parser; possible values are 0 and 1. Unless specified, XML::LibXML sets this option to 0. πŸ‘€

Note: the default value for this option was changed to protect against denial of service through entity expansion attacks. Before enabling the option ensure you have taken alternative measures to protect your application against this type of attack. πŸ›‘οΈ fr fr, do not skip this one.

πŸ‘‘ gdome

/parser/

THIS OPTION IS EXPERIMENTAL! πŸ’€

Although quite powerful, XML::LibXML's DOM implementation is incomplete with respect to the DOM level 2 or level 3 specifications. XML::GDOME is based on libxml2 as well, and provides a rather complete DOM implementation by wrapping libgdome. This flag allows you to make use of XML::LibXML's full parser options and XML::GDOME's DOM implementation at the same time. ✨

To make use of this function, one has to install libgdome and configure XML::LibXML to use this library. For this you need to rebuild XML::LibXML! 😭

Note: this feature was not seriously tested in recent XML::LibXML releases. πŸ™ˆ


🌈 the pre-1.70 compatibility era

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):

$parser->validation();
$parser->recover();
$parser->pedantic_parser();
$parser->line_numbers();
$parser->load_ext_dtd();
$parser->complete_attributes();
$parser->expand_xinclude();
$parser->gdome_dom();
$parser->clean_namespaces();
$parser->no_network();

🌸 the obsolete methods (they still hit, but they hit weird)

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

πŸ’œ recover_silently

$parser->recover_silently(1);

If called without an argument, returns true if the current value of the recover parser option is 2 and returns false otherwise. With a true argument sets the recover parser option to 2; with a false argument sets the recover parser option to 0. 🀫

πŸ’œ expand_entities

$parser->expand_entities(0);

Get/set the expand_entities option. If called with a true argument, also turns the load_ext_dtd option to 1. 🧚

πŸ’œ keep_blanks

$parser->keep_blanks(0);

This is actually the opposite of the no_blanks parser option. If used without an argument retrieves negated value of no_blanks. If used with an argument sets no_blanks to the opposite value. πŸ™ƒ

πŸ’œ base_uri

$parser->base_uri( $your_base_uri );

Get/set the URI option. πŸŽ€

πŸ¦‹ XML CATALOGS πŸ¦‹

Okay so libxml2 supports XML catalogs, and catalogs are literally just a way to map remote resources to their local copies. Why do you care? Because using catalogs can speed up parsing processes if you're loading a ton of external resources from remote addresses into your parsed documents (think DTDs or XIncludes). It's giving glow up for your parse times ✨.

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). No cap, it's global bestie.
Also note 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. Pick a lane πŸ’….

πŸ“‚ load_catalog

$parser->load_catalog( $catalog_file );

Loads the XML catalog file $catalog_file.

# Global external entity loader (similar to ext_ent_handler option
# but this works really globally, also in XML::LibXSLT include etc..)

XML::LibXML::externalEntityLoader(\&my_loader);

😭 ERROR REPORTING 😭

XML::LibXML throws exceptions during parsing, validation or XPath processing (and some other occasions, because of course it does πŸ’€). 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
  • 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). So like… protect your peace and wrap it, bestie 🫢.

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. Fr fr.

Note: since version 1.59, get_last_error() is no longer available in XML::LibXML for thread-safety reasons. She's gone, she's not coming back πŸ™ˆ.

πŸ‘‘ AUTHORS πŸ‘‘

Matt Sergeant, Christian Glahn, Petr Pajas


⭐ VERSION ⭐

2.0213


2001-2007, AxKit.com Ltd.

2002-2006, Christian Glahn.

2006-2009, Petr Pajas.


🌈 LICENSE 🌈

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


And that's the whole vibe check, bestie β€” this lil page is from perl v5.42.2, dated 2026-05-25, and it's the one and only XML::Li...::Parser(3) πŸ’– Go forth and parse, you absolute icon βœ¨πŸ¦‹πŸ’…

πŸ“¦ where this page comes from