XML::LibXML - Interface to the gnome libxml2 library use XML::LibXML; my $parser = XML::LibXML->new(); my $doc = $parser->parse_string(<<'EOT'); <some-xml/> EOT This module is an interface to the gnome libxml2 DOM parser (no SAX parser support yet), and the DOM tree. It also provides an XML::XPath-like findnodes() interface, providing access to the XPath API in libxml2. LibXML options are global (unfortunately this is a limitation of the underlying implementation, not this interface). They can either be set using `$parser->option(...)', or `XML::LibXML->option(...)', both are treated in the same manner. Note that even two forked processes will share some of the same options, so be careful out there! Every option returns the previous value, and can be called without parameters to get the current value.

validation
$parser->validation(1); Turn validation on (or off). Defaults to off.

expand_entities
$parser->expand_entities(0); Turn entity expansion on or off, enabled by default. If entity expansion is off, any external parsed entities in the document are left as entities. Probably not very useful for most purposes.

keep_blanks
$parser->keep_blanks(0); Allows you to turn off XML::LibXML's default behaviour of maintaining whitespace in the document.

pedantic_parser
$parser->pedantic_parser(1); You can make XML::LibXML more pedantic if you want to.

load_ext_dtd
$parser->load_ext_dtd(1); Load external DTD subsets while parsing.

complete_attributes
$parser->complete_attributes(1); Complete the elements attributes lists with the ones defaulted from the DTDs. By default, this option is enabled.

expand_xinclude
$parser->expand_xinclude Expands XIinclude tags imidiatly while parsing the document. This flag ashures that the parser callbacks are used while parsing the included Document.

match_callback
$parser->match_callback($subref); Sets a "match" callback. See the section on "Input Callbacks" below.

open_callback
$parser->open_callback($subref); Sets an open callback. See the section on "Input Callbacks" below.

read_callback
$parser->read_callback($subref); Sets a read callback. See the section on "Input Callbacks" below.

close_callback
$parser->close_callback($subref); Sets a close callback. See the section on "Input Callbacks" below. The XML::LibXML constructor, `new()', takes the following parameters:

ext_ent_handler
my $parser = XML::LibXML->new(ext_ent_handler => sub { ... }); The ext_ent_handler sub is called whenever libxml needs to load an external parsed entity. The handler sub will be passed two parameters: a URL (SYSTEM identifier) and an ID (PUBLIC identifier). It should return a string containing the resource at the given URI. Note that you do not need to enable this - if not supplied libxml will get the resource either directly from the filesystem, or using an internal http client library. There are three ways to parse documents - as a string, as a Perl filehandle, or as a filename. The return value from each is a XML::LibXML::Document object, which is a DOM object (although not all DOM methods are implemented yet). See the section on "XML::LibXML::Document" below for more details on the methods available on documents. Each of the below methods will throw an exception if the document is invalid. To prevent this causing your program exiting, wrap the call in an eval{} block.

parse_string
my $doc = $parser->parse_string($string); or, passing in a directory to use as the "base": my $doc = $parser->parse_string($string, $dir);

parse_fh
my $doc = $parser->parse_fh($fh); Here, `$fh' can be an IOREF, or a subclass of IO::Handle. And again, you can pass in a directory as the "base": my $doc = $parser->parse_fh($fh, $dir); Note in the above two cases, $dir must end in a trailing slash, otherwise the parent of that directory is used. This can actually be useful, in that it will accept the filename of what you're parsing.

parse_file
my $doc = $parser->parse_file($filename); As of version 0.96, XML::LibXML is capable of parsing HTML into a regular XML DOM. This gives you the full power of XML::LibXML on HTML documents. The methods work in exactly the same way as the methods above, and return exactly the same type of object. If you wish to dump the resulting document as HTML again, you can use `$doc-'toStringHTML()> to do that.

parse_html_string
my $doc = $parser->parse_html_string($string);

parse_html_fh
my $doc = $parser->parse_html_fh($fh);

parse_html_file
my $doc = $parser->parse_html_file($filename);

Extra parsing methods
processXIncludes $parser->processXIncludes( $doc ); While the document class implements a separate XInclude processing, this method, is stricly related to the parser. The use of this method is only required, if the parser implements special callbacks that should to be used for the XInclude as well. If expand_xincludes is set to 1, the method is only required to process XIncludes appended to the DOM after its original parsing. The objects returned above have a few methods available to them:

`$doc->toString'
Convert the document to a string.

`$doc->is_valid'
Post parse validation. Returns true if the document is valid against the DTD specified in the DOCTYPE declaration

`$doc->is_valid($dtd)'
Same as the above, but allows you to pass in a DTD created from the section on "XML::LibXML::Dtd".

`$doc->process_xinclude'
Process any xinclude tags in the file. (currently using only libxml2's default callbacks) This module allows you to parse and return a DTD object. It has one method right now, `new()'.

new()
my $dtd = XML::LibXML::Dtd->new($public, $system); Creates a new DTD object from the public and system identifiers. It will automatically load the objects from the filesystem, or use the input callbacks (see the section on "Input Callbacks" below) to load the DTD. The input callbacks are used whenever LibXML has to get something other than external parsed entities from somewhere. The input callbacks in LibXML are stacked on top of the original input callbacks within the libxml library. This means that if you decide not to use your own callbacks (see `match()'), then you can revert to the default way of handling input. This allows, for example, to only handle certain URI schemes. Callbacks are only used on files, but not on strings or filehandles. This is because LibXML requires the match event to find out about which callback set is shall be used for the current input stream. LibXML can decide this only before the stream is open. For LibXML strings and filehandles are already opened streams. The following callbacks are defined:

match(uri)
If you want to handle the URI, simply return a true value from this callback.

open(uri)
Open something and return it to handle that resource.

read(handle, bytes)
Read a certain number of bytes from the resource. This callback is called even if the entire Document has already read.

close(handle)
Close the handle associated with the resource.

Example
This is a purely fictitious example that uses a MyScheme::Handler object that responds to methods similar to an IO::Handle. $parser->match_callback(\&match_uri); $parser->open_callback(\&open_uri); $parser->read_callback(\&read_uri); $parser->close_callback(\&close_uri); sub match_uri { my $uri = shift; return $uri =~ /^myscheme:/; } sub open_uri { my $uri = shift; return MyScheme::Handler->new($uri); } sub read_uri { my $handler = shift; my $length = shift; my $buffer; read($handler, $buffer, $length); return $buffer; } sub close_uri { my $handler = shift; close($handler); } A more realistic example can be found in the the section on "example" directory All data will be stored UTF-8 encoded. Nevertheless the input and output functions are aware about the encoding of the owner document. By default all functions will assume, UTF-8 encoding of the passed strings unless the owner document has a different encoding. In such a case the functions will assume the encoding of the document to be valid. At the current state of implementation query functions like findnodes(), getElementsByTagName() or getAttribute() accept only UTF-8 encoded strings, even if the underlaying document has a different encoding. At first this seems to be a limitation, but on application level there is no way to make save asumptations about the encoding of the strings. Future releases will offer the opportunity to force an application wide encoding, so make shure that you installed the latest version of XML::LibXML. To encode or decode a string to or from UTF-8 XML::LibXML exports two functions, which use the encoding mechanism of the underlaying implementation. These functions should be used, if external encoding is required (e.g. for queryfunctions).

encodeToUTF8
$encodedstring = encodeToUTF8( $name_of_encoding, $sting_to_encode ); The function will encode a string from the specified encoding to UTF-8.

decodeFromUTF8
$decodedstring = decodeFromUTF8($name_of_encoding, $string_to_decode ); This Function transforms an UTF-8 encoded string the specified encoding. While transforms to ISO encodings may cause errors if the given stirng contains unsupported characters, this function can transform to UTF-16 encodings as well. Processing instructions are implemented with XML::LibXML with read and write access ;) The pi data is the pi without the pi target (as specified in XML 1.0 [17]) as a string. This string can be accessed with the getData manpage as implemented in XML::LibXML::Node. The write access is aware about the fact, that many processing instructions have attribute like data. Therefor the setData manpage provides besides the DOM spec conform Interface to pass a set of named parameter. So the code segment my $pi = $dom->createProcessingInstruction("abc"); $pi->setData(foo=>'bar', foobar=>'foobar'); $dom->appendChild( $pi ); will result the following pi in the DOM: <?abc foo="bar" foobar="foobar"?> The same can be done with $pi->setData( 'foo="bar" foobar="foobar"' ); Which is how it is specified in the the DOM specification entry elsewhere in this document. This three step interface creates temporary a node in perl space. This can be avoided while using the insertProcessingInstruction method. Instead of the three calls described above, the call `$dom-'insertProcessingInstruction("abc",'foo="bar" foobar="foobar"');> will have the same result as above. Currently only the setData() function accepts named parameters, while only strings are accepted by the other methods.

createProcessingInstruction
SYNOPSIS: $pinode = $dom->createProcessingInstruction( $target ); or $pinode = $dom->createProcessingInstruction( $target, $data ); This function creates a new pi and returns this node. The pi is bound to the DOM, but is not appended to the DOM itself. To add the pi to the DOM, one needs to use appendChild() directly on the dom itself.

insertProcessingInstruction
SYNOPSIS: $dom->insertProcessingInstruction( $target, $data ); Creates a processing instruction and inserts it directly to the DOM. The function does not return a node.

createPI
alias for createProcessingInstruction

insertPI
alias for insertProcessingInstruction

setData
SYNOPSIS: $pinode->setData( $data_string ); or $pinode->setData( name=>string_value [...] ); This method allows to change the content data of a pi. Additionaly to the interface specified for DOM Level2, the method provides a named parameter interface to set the data. This parameterlist is converted into a string before it is appended to the pi. Matt Sergeant, matt@sergeant.org Copyright 2001, AxKit.com Ltd. All rights reserved. the XML::LibXSLT manpage, the XML::LibXML::Document manpage, the XML::LibXML::Element manpage, the XML::LibXML::Node manpage, the XML::LibXML::Text manpage, the XML::LibXML::Comment manpage, the XML::LibXML::CDATASection manpage, the XML::LibXML::Attribute manpage the XML::LibXML::DocumentFragment manpage