XML::Li...Document(3)
π XML::LibXML::Document β the DOM Document Class π
okay bestie, welcome to the XML::LibXML::Document page (it's a User Contributed Perl Documentation situation, section 3, iykyk). This is the big one. The whole document object. Let's get into it π«Ά
β¨ SYNOPSIS β¨
like, here's the whole vibe in code form:
use XML::LibXML;
# Only methods specific to Document nodes are listed here,
# see the XML::LibXML::Node manpage for other methods
$dom = XML::LibXML::Document->new( $version, $encoding );
$dom = XML::LibXML::Document->createDocument( $version, $encoding );
$strURI = $doc->URI();
$doc->setURI($strURI);
$strEncoding = $doc->encoding();
$strEncoding = $doc->actualEncoding();
$doc->setEncoding($new_encoding);
$strVersion = $doc->version();
$doc->standalone
$doc->setStandalone($numvalue);
my $compression = $doc->compression;
$doc->setCompression($ziplevel);
$docstring = $dom->toString($format);
$c14nstr = $doc->toStringC14N($comment_flag, $xpath_expression [, $xpath_context ]);
$ec14nstr = $doc->toStringEC14N($comment_flag, $xpath_expression [, $xpath_context ], $inclusive_prefix_list);
$str = $doc->serialize($format);
$state = $doc->toFile($filename, $format);
$state = $doc->toFH($fh, $format);
$str = $document->toStringHTML();
$str = $document->serialize_html();
$bool = $dom->is_valid();
$dom->validate();
$root = $dom->documentElement();
$dom->setDocumentElement( $root );
$element = $dom->createElement( $nodename );
$element = $dom->createElementNS( $namespaceURI, $nodename );
$text = $dom->createTextNode( $content_text );
$comment = $dom->createComment( $comment_text );
$attrnode = $doc->createAttribute($name [,$value]);
$attrnode = $doc->createAttributeNS( namespaceURI, $name [,$value] );
$fragment = $doc->createDocumentFragment();
$cdata = $dom->createCDATASection( $cdata_content );
my $pi = $doc->createProcessingInstruction( $target, $data );
my $entref = $doc->createEntityReference($refname);
$dtd = $document->createInternalSubset( $rootnode, $public, $system);
$dtd = $document->createExternalSubset( $rootnode_name, $publicId, $systemId);
$document->importNode( $node );
$document->adoptNode( $node );
my $dtd = $doc->externalSubset;
my $dtd = $doc->internalSubset;
$doc->setExternalSubset($dtd);
$doc->setInternalSubset($dtd);
my $dtd = $doc->removeExternalSubset();
my $dtd = $doc->removeInternalSubset();
my @nodelist = $doc->getElementsByTagName($tagname);
my @nodelist = $doc->getElementsByTagNameNS($nsURI,$tagname);
my @nodelist = $doc->getElementsByLocalName($localname);
my $node = $doc->getElementById($id);
$dom->indexElements();
πΈ DESCRIPTION πΈ
So the Document Class? Most of the time it's literally just the glow-up result of a parsing process. But sometimes you gotta build a Document from absolute scratch, no parsing involved, and that's valid too π . The DOM Document Class hands you functions that play nice with the DOM Core naming style, so if you know DOM, you already know the vibe.
It inherits everything from XML::LibXML::Node as laid out in the DOM spec. That means you can reach the nodes that live next to the root element at document level β a "DTD" for example (yes the quotes are part of the original, iconic). The support for those nodes is limited at the moment, ngl.
Here's the tea though: in the DOM concept, nodes are bound to a document, but the recommendation is you should always create a node that isn't bound to any document. You don't actually need to include the node in the document β but the moment a node is bound to a document, you can be pretty safe that all the strings carry the correct encoding. If you create an unbound text node with an ISO encoded string (like, say, with $CLASS->new()), the "toString" function might not give you the result you were expecting π.
To dodge all that mess, the move is: pass all your data to XML::LibXML methods as character strings (i.e. UTF-8 encoded, with the UTF8 flag on). periodt.
π METHODS π
Lowkey a lot of these are documented to death in the DOM Level 3 specification (<http://www.w3.org/TR/DOM-Level-3-Core/>). So if you want the extensive lore, go read the spec, bestie.
π new
$dom = XML::LibXML::Document->new( $version, $encoding );
it's an alias for createDocument() β same energy, shorter name.
π createDocument
$dom = XML::LibXML::Document->createDocument( $version, $encoding );
The constructor for the document class, the main character of this section π. As parameters it takes the version string and (optionally) the encoding string. Calling createDocument() plain and simple gives you:
<?xml version="your version" encoding="your encoding"?>
Both params are optional, no pressure. The default value for $version is 1.0, of course, as it should be. If $encoding isn't set, the encoding stays unset, which means UTF-8 is implied.
So calling createDocument() with zero parameters gives you back:
<?xml version="1.0"?>
Alternatively you can call this constructor straight from the XML::LibXML class level, to save yourself some typing. This has no effect on the class instance, which is always XML::LibXML::Document:
my $document = XML::LibXML->createDocument( "1.0", "UTF-8" );
which is therefore just a shortcut for
my $document = XML::LibXML::Document->createDocument( "1.0", "UTF-8" );
π URI
$strURI = $doc->URI();
Returns the URI (or filename) of the original document. For documents you got by parsing a string or a FH without using the URI parsing argument of the matching "parse_*" function, the result is a generated string unknown-XYZ where XYZ is some number. For documents created with the "new" constructor, the URI is undefined.
You can change this value by calling the "setURI" method on the document node.
π setURI
$doc->setURI($strURI);
Sets the URI of the document β the one reported by the URI method (see also the URI argument to the various "parse_*" functions).
π encoding
$strEncoding = $doc->encoding();
returns the encoding string of the document, simple as:
my $doc = XML::LibXML->createDocument( "1.0", "ISO-8859-15" );
print $doc->encoding; # prints ISO-8859-15
π actualEncoding
$strEncoding = $doc->actualEncoding();
returns the encoding in which the XML will actually come back from $doc->toString(). Usually that's the original encoding of the document as declared in the XML declaration and returned by $doc->encoding. But if the original encoding isn't known (say it was created in memory, or parsed from XML with no declared encoding), 'UTF-8' is returned.
my $doc = XML::LibXML->createDocument( "1.0", "ISO-8859-15" );
print $doc->encoding; # prints ISO-8859-15
π setEncoding
$doc->setEncoding($new_encoding);
This one lets you change the declaration of encoding in the XML declaration of the document. The value also affects the encoding the document gets serialized to XML in, via $doc->toString(). Use setEncoding() to remove the encoding declaration entirely.
π version
$strVersion = $doc->version();
returns the version string of the document.
getVersion() is an alternative form of this function.
π standalone
$doc->standalone
This returns the numerical value of a document's XML declaration standalone attribute. It hands back 1 if standalone="yes" was found, 0 if standalone="no" was found, and -1 if standalone wasn't specified at all (which is the default on creation).
π setStandalone
$doc->setStandalone($numvalue);
Through this method you can alter the value of a document's standalone attribute. Set it to 1 for standalone="yes", to 0 for standalone="no", or to -1 to straight up remove the standalone attribute from the XML declaration.
π compression
my $compression = $doc->compression;
libxml2 lets you read documents directly from gzipped files, which is a slay. In that case the compression variable is set to the compression level of that file (0-8). If XML::LibXML parsed a different source, or the file wasn't compressed, the returned value will be -1.
π setCompression
$doc->setCompression($ziplevel);
If you're planning to write the document directly to a file, you can set the compression level for a given document. This level can be in the range from 0 to 8. If XML::LibXML shouldn't try to compress at all, use -1 (the default).
Note that this feature will only work if libxml2 is compiled with zlib support and toFile() is used for output.
π toString
$docstring = $dom->toString($format);
toString is a DOM serializing function, so the DOM Tree gets serialized into an XML string, ready for output. β¨
IMPORTANT: unliketoStringfor other nodes, on document nodes this function returns the XML as a byte string in the original encoding of the document (see theactualEncoding()method)! This means you can simply do:perl open my $out_fh, '>', $file; print {$out_fh} $doc->toString;regardless of the actual encoding of the document. See the section on encodings in XML::LibXML for more details.
The optional $format parameter sets the indenting of the output. It's expected to be an "integer" value, which specifies that indentation should be used. The format parameter can have three different values if you use it:
- If
$formatis0, then the document is dumped as it was originally parsed - If
$formatis1, libxml2 will add ignorable white spaces, so the nodes content is easier to read. Existing text nodes will not be altered - If
$formatis2(or higher), libxml2 will act as$format == 1but it adds a leading and a trailing line break to each text node.
libxml2 uses a hard-coded indentation of 2 space characters per indentation level. This value can not be altered on run-time. periodt.
π toStringC14N
$c14nstr = $doc->toStringC14N($comment_flag, $xpath_expression [, $xpath_context ]);
See the documentation in XML::LibXML::Node. (iykyk, the lore lives over there π«)
π toStringEC14N
$ec14nstr = $doc->toStringEC14N($comment_flag, $xpath_expression [, $xpath_context ], $inclusive_prefix_list);
See the documentation in XML::LibXML::Node.
π serialize
$str = $doc->serialize($format);
An alias for toString(). This function was name added to be more consistent with libxml2 (yes, that's literally how it's phrased, keeping it fr fr).
π serialize_c14n
An alias for toStringC14N().
π serialize_exc_c14n
An alias for toStringEC14N().
π toFile
$state = $doc->toFile($filename, $format);
This function is similar to toString(), but it writes the document directly into a filesystem. Super useful when you need to store large documents, no cap.
The format parameter has the same behaviour as in toString().
π toFH
$state = $doc->toFH($fh, $format);
Like, this one is toString()'s chaotic extrovert sibling π β it's similar to toString(), but instead of handing you back a string, it writes the document straight to a filehandle or a stream. What shows up on the other end is a byte stream in the document encoding, passed to the filehandle.
π¨ BESTIE LISTEN: do NOT slap any:encoding(...)or":utf8"PerlIO layer on that filehandle! Not the vibe. For the full tea, go read the section on encodings in XML::LibXML.
The format parameter behaves exactly the same as it does in toString(). Same rules, different destination. Periodt.
β¨ toStringHTML β¨
$str = $document->toStringHTML();
toStringHTML serializes the tree into a byte string in the document encoding, but as HTML. π And with this method, indenting is automatic and managed by libxml2 internally β no notes, it just does it.
Heads up though: the string must contain<meta http-equiv="Content-Type" content="text/html; charset=utf-8">(and not the newer<meta charset="utf-8">), otherwise all your non-ASCII characters become entities. π
π¦ serialize_html π¦
$str = $document->serialize_html();
An alias for toStringHTML(). Same girl, different name. π
πΈ is_valid πΈ
$bool = $dom->is_valid();
Returns either TRUE or FALSE, depending on whether the DOM Tree is a valid Document or not. Simple as that, no cap.
You can also pass in an XML::LibXML::Dtd object, to validate against an external DTD:
if (!$dom->is_valid($dtd)) {
warn("document is not valid!");
}
π validate π
$dom->validate();
This is the exception-throwing equivalent of is_valid. If the document isn't valid it will throw an exception containing the error β which honestly gives you way better error reporting than just a flat is_valid or not. Main character error handling. π
And again, you may pass in a DTD object.
π documentElement π
$root = $dom->documentElement();
Returns the root element of the Document. A document can have just one root element to contain the document's data. One root, one crown, that's the rule.
Optionally one can use getDocumentElement.
β¨ setDocumentElement β¨
$dom->setDocumentElement( $root );
This function lets you set the root element for a document. It supports importing a node from a different document tree, but it does not support a document fragment as $root. π«
π§ createElement π§
$element = $dom->createElement( $nodename );
Creates a new Element Node bound to the DOM with the name $nodename.
π¦ createElementNS π¦
$element = $dom->createElementNS( $namespaceURI, $nodename );
Creates a new Element Node bound to the DOM with the name $nodename, placed in the given namespace. Namespace glow-up. β¨
π createTextNode π
$text = $dom->createTextNode( $content_text );
Basically the createElement equivalent, but it creates a Text Node bound to the DOM.
πΈ createComment πΈ
$comment = $dom->createComment( $comment_text );
Same energy as createElement, except this one creates a Comment Node bound to the DOM. π¬
π
createAttribute π
$attrnode = $doc->createAttribute($name [,$value]);
Creates a new Attribute node. Boom.
β createAttributeNS β
$attrnode = $doc->createAttributeNS( namespaceURI, $name [,$value] );
Creates an Attribute bound to a namespace.
π createDocumentFragment π
$fragment = $doc->createDocumentFragment();
This function creates a DocumentFragment.
π createCDATASection π
$cdata = $dom->createCDATASection( $cdata_content );
Similar to createTextNode and createComment, this function creates a CDataSection bound to the current DOM.
π₯ createProcessingInstruction π₯
my $pi = $doc->createProcessingInstruction( $target, $data );
Creates a processing instruction node. π―
Since this method name is, like, so long, you may use its short form createPI().
π«Ά createEntityReference π«Ά
my $entref = $doc->createEntityReference($refname);
If a document has a DTD specified, you can create entity references with this function. And if you want to add an entity reference to the document, this is the function that has to create it. No shortcuts, bestie.
An entity reference is unique to a document and cannot be passed to other documents the way other nodes can. It's loyal like that. π
NOTE: a text content containing something that looks like an entity reference will not be expanded into a real entity reference unless it's a predefined entity.
my $string = "&foo;";
$some_element->appendText( $string );
print $some_element->textContent; # prints "&foo;"
π§ createInternalSubset π§
$dtd = $document->createInternalSubset( $rootnode, $public, $system);
This function creates and adds an internal subset to the given document. And because it automatically adds the DTD to the document, there's no need to add the created node explicitly yourself. It just handles it. π
my $document = XML::LibXML::Document->new();
my $dtd = $document->createInternalSubset( "foo", undef, "foo.dtd" );
...will result in the following XML document:
<?xml version="1.0"?>
<!DOCTYPE foo SYSTEM "foo.dtd">
By setting the public parameter it's possible to set PUBLIC DTDs on a given document. So:
my $document = XML::LibXML::Document->new();
my $dtd = $document->createInternalSubset( "foo", "-//FOO//DTD FOO 0.1//EN", undef );
...will cause the following declaration to be created on the document:
<?xml version="1.0"?>
<!DOCTYPE foo PUBLIC "-//FOO//DTD FOO 0.1//EN">
πΈ createExternalSubset πΈ
$dtd = $document->createExternalSubset( $rootnode_name, $publicId, $systemId);
This one's similar to createInternalSubset(), except this DTD counts as external and therefore is not added to the document itself. Still, it can absolutely be used for validation purposes. β¨
π importNode π
$document->importNode( $node );
If a node isn't part of a document, it can be imported into another document. As specified in the DOM Level 2 Specification, the Node will not be altered or removed from its original document ("$node->cloneNode(1)" gets called implicitly).
β οΈ NOTE: Don't try to use importNode() to import sub-trees that contain an entity reference β even if the entity reference is the root node of the sub-tree. This will cause serious problems to your program. It's a limitation of libxml2 and not of XML::LibXML itself. Not our fault, but still your problem. π
π¦ adoptNode π¦
$document->adoptNode( $node );
If a node isn't part of a document, it can be imported into another document. As specified in the DOM Level 3 Specification, the Node will not be altered β but it will be removed from its original document. Glow-up + relocation arc. π§³
After a document adopts a node, that node, its attributes and all its descendants belong to the new document. And because the node no longer belongs to the old document, it gets unlinked from its old location first.
β οΈ NOTE: Don't try to adoptNode() to import sub-trees that contain entity references β even if the entity reference is the root node of the sub-tree. This will cause serious problems to your program. Again: limitation of libxml2, not of XML::LibXML itself.
π externalSubset π
my $dtd = $doc->externalSubset;
If a document has an external subset defined, this function returns it.
NOTE: Dtd nodes are not ordinary nodes in libxml2. Support for these nodes in XML::LibXML is still limited. In particular, you may not want to use common node functions on doctype declaration nodes! π©
π internalSubset π
my $dtd = $doc->internalSubset;
If a document has an internal subset defined, this function returns it.
NOTE: Dtd nodes are not ordinary nodes in libxml2. Support for these nodes in XML::LibXML is still limited. In particular, you may not want to use common node functions on doctype declaration nodes! π©
π§ͺ setExternalSubset π§ͺ
$doc->setExternalSubset($dtd);
EXPERIMENTAL! π§ͺ
This method sets a DTD node as an external subset of the given document.
π§ͺ setInternalSubset π§ͺ
$doc->setInternalSubset($dtd);
EXPERIMENTAL! π§ͺ
This method sets a DTD node as an internal subset of the given document.
π§ͺ removeExternalSubset π§ͺ
my $dtd = $doc->removeExternalSubset();
EXPERIMENTAL! π§ͺ
If a document has an external subset defined, it can be removed from the document with this function. The removed dtd node gets returned to you. π
π§ͺ removeInternalSubset π§ͺ
my $dtd = $doc->removeInternalSubset();
EXPERIMENTAL! π§ͺ
If a document has an internal subset defined, it can be removed from the document with this function. The removed dtd node gets returned.
π getElementsByTagName π
my @nodelist = $doc->getElementsByTagName($tagname);
Implements the DOM Level 2 function.
In SCALAR context this function returns an XML::LibXML::NodeList object.
π getElementsByTagNameNS π
my @nodelist = $doc->getElementsByTagNameNS($nsURI,$tagname);
Implements the DOM Level 2 function.
In SCALAR context this function returns an XML::LibXML::NodeList object.
π getElementsByLocalName π
my @nodelist = $doc->getElementsByLocalName($localname);
This lets you fetch all nodes from a given document with the given Localname.
In SCALAR context this function returns an XML::LibXML::NodeList object.
π getElementById π
my $node = $doc->getElementById($id);
Returns the element that has an ID attribute with the given value. If no such element exists, it returns undef. π
Note: the ID of an element may change while you're manipulating the document. For documents with a DTD, the information about ID attributes is only available if DTD loading/validation has been requested. For HTML documents parsed with the HTML parser, ID detection is done automatically. In XML documents, all "xml:id" attributes are considered to be of type ID. And you can test ID-ness of an attribute node with $attr->isId().
In versions 1.59 and earlier this method was called getElementsById() (plural) by mistake. Starting from 1.60 this name is maintained as an alias only for backward compatibility. iykyk π
β indexElements β
$dom->indexElements();
Okay so this one function β the indexing one β literally calls up libxml2 and makes it stamp every single element in a document with its document position index. And bestie, the glow-up is real: XPath queries on big documents get considerably faster. β¨
β οΈ But here's the catch, and I need you to hear me on this: only use it on static documents that nothing else is gonna touch with DOM methods afterwards. Because once a document is indexed, XPath will always prefer the index over every other way of figuring out node order. So if you index a doc and then mutate it, your XPath can hand you back improperly ordered node-lists. π Not a vibe.
The save? You can totally just call this method again to re-index a modified document before running XPath on it again. π«Ά
And just so we're clear β this function is not a part of the DOM specification. It's a bonus, not a rule. π
So what does it hand back?
- the number of elements indexed, when everything goes great π
-1if an error occurred π-2if this feature isn't available in the runninglibxml2π
π AUTHORS
Matt Sergeant, Christian Glahn, Petr Pajas
The trio. The icons. The main characters. β¨
β VERSION
2.0213
π COPYRIGHT
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 page, bestie!! This doc is perl v5.42.2, dated 2026-05-25, and it's the XML::Li...Document(3) page from the User Contributed Perl Documentation. Go forth and index responsibly β no cap. π
π
π¦ where this page comes from
- fedora 43: perl-XML-LibXML 1:2.0213-1.fc43 Β· (GPL-1.0-or-later OR Artistic-1.0-Perl) AND MIT
- fedora 44: perl-XML-LibXML 1:2.0213-1.fc44 Β· (GPL-1.0-or-later OR Artistic-1.0-Perl) AND MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms