{
    "mode": "perldoc",
    "parameter": "XML::LibXML::Document",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/XML%3A%3ALibXML%3A%3ADocument/json",
    "generated": "2026-06-09T16:07:52Z",
    "synopsis": "use XML::LibXML;\n# Only methods specific to Document nodes are listed here,\n# see the XML::LibXML::Node manpage for other methods\n$dom = XML::LibXML::Document->new( $version, $encoding );\n$dom = XML::LibXML::Document->createDocument( $version, $encoding );\n$strURI = $doc->URI();\n$doc->setURI($strURI);\n$strEncoding = $doc->encoding();\n$strEncoding = $doc->actualEncoding();\n$doc->setEncoding($newencoding);\n$strVersion = $doc->version();\n$doc->standalone\n$doc->setStandalone($numvalue);\nmy $compression = $doc->compression;\n$doc->setCompression($ziplevel);\n$docstring = $dom->toString($format);\n$c14nstr = $doc->toStringC14N($commentflag, $xpath [, $xpathcontext ]);\n$ec14nstr = $doc->toStringEC14N($commentflag, $xpath [, $xpathcontext ], $inclusiveprefixlist);\n$str = $doc->serialize($format);\n$state = $doc->toFile($filename, $format);\n$state = $doc->toFH($fh, $format);\n$str = $document->toStringHTML();\n$str = $document->serializehtml();\n$bool = $dom->isvalid();\n$dom->validate();\n$root = $dom->documentElement();\n$dom->setDocumentElement( $root );\n$element = $dom->createElement( $nodename );\n$element = $dom->createElementNS( $namespaceURI, $nodename );\n$text = $dom->createTextNode( $contenttext );\n$comment = $dom->createComment( $commenttext );\n$attrnode = $doc->createAttribute($name [,$value]);\n$attrnode = $doc->createAttributeNS( namespaceURI, $name [,$value] );\n$fragment = $doc->createDocumentFragment();\n$cdata = $dom->createCDATASection( $cdatacontent );\nmy $pi = $doc->createProcessingInstruction( $target, $data );\nmy $entref = $doc->createEntityReference($refname);\n$dtd = $document->createInternalSubset( $rootnode, $public, $system);\n$dtd = $document->createExternalSubset( $rootnodename, $publicId, $systemId);\n$document->importNode( $node );\n$document->adoptNode( $node );\nmy $dtd = $doc->externalSubset;\nmy $dtd = $doc->internalSubset;\n$doc->setExternalSubset($dtd);\n$doc->setInternalSubset($dtd);\nmy $dtd = $doc->removeExternalSubset();\nmy $dtd = $doc->removeInternalSubset();\nmy @nodelist = $doc->getElementsByTagName($tagname);\nmy @nodelist = $doc->getElementsByTagNameNS($nsURI,$tagname);\nmy @nodelist = $doc->getElementsByLocalName($localname);\nmy $node = $doc->getElementById($id);\n$dom->indexElements();",
    "sections": {
        "NAME": {
            "content": "XML::LibXML::Document - XML::LibXML DOM Document Class\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use XML::LibXML;\n# Only methods specific to Document nodes are listed here,\n# see the XML::LibXML::Node manpage for other methods\n\n$dom = XML::LibXML::Document->new( $version, $encoding );\n$dom = XML::LibXML::Document->createDocument( $version, $encoding );\n$strURI = $doc->URI();\n$doc->setURI($strURI);\n$strEncoding = $doc->encoding();\n$strEncoding = $doc->actualEncoding();\n$doc->setEncoding($newencoding);\n$strVersion = $doc->version();\n$doc->standalone\n$doc->setStandalone($numvalue);\nmy $compression = $doc->compression;\n$doc->setCompression($ziplevel);\n$docstring = $dom->toString($format);\n$c14nstr = $doc->toStringC14N($commentflag, $xpath [, $xpathcontext ]);\n$ec14nstr = $doc->toStringEC14N($commentflag, $xpath [, $xpathcontext ], $inclusiveprefixlist);\n$str = $doc->serialize($format);\n$state = $doc->toFile($filename, $format);\n$state = $doc->toFH($fh, $format);\n$str = $document->toStringHTML();\n$str = $document->serializehtml();\n$bool = $dom->isvalid();\n$dom->validate();\n$root = $dom->documentElement();\n$dom->setDocumentElement( $root );\n$element = $dom->createElement( $nodename );\n$element = $dom->createElementNS( $namespaceURI, $nodename );\n$text = $dom->createTextNode( $contenttext );\n$comment = $dom->createComment( $commenttext );\n$attrnode = $doc->createAttribute($name [,$value]);\n$attrnode = $doc->createAttributeNS( namespaceURI, $name [,$value] );\n$fragment = $doc->createDocumentFragment();\n$cdata = $dom->createCDATASection( $cdatacontent );\nmy $pi = $doc->createProcessingInstruction( $target, $data );\nmy $entref = $doc->createEntityReference($refname);\n$dtd = $document->createInternalSubset( $rootnode, $public, $system);\n$dtd = $document->createExternalSubset( $rootnodename, $publicId, $systemId);\n$document->importNode( $node );\n$document->adoptNode( $node );\nmy $dtd = $doc->externalSubset;\nmy $dtd = $doc->internalSubset;\n$doc->setExternalSubset($dtd);\n$doc->setInternalSubset($dtd);\nmy $dtd = $doc->removeExternalSubset();\nmy $dtd = $doc->removeInternalSubset();\nmy @nodelist = $doc->getElementsByTagName($tagname);\nmy @nodelist = $doc->getElementsByTagNameNS($nsURI,$tagname);\nmy @nodelist = $doc->getElementsByLocalName($localname);\nmy $node = $doc->getElementById($id);\n$dom->indexElements();\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "The Document Class is in most cases the result of a parsing process. But sometimes it is\nnecessary to create a Document from scratch. The DOM Document Class provides functions that\nconform to the DOM Core naming style.\n\nIt inherits all functions from XML::LibXML::Node as specified in the DOM specification. This\nenables access to the nodes besides the root element on document level - a \"DTD\" for example.\nThe support for these nodes is limited at the moment.\n\nWhile generally nodes are bound to a document in the DOM concept it is suggested that one should\nalways create a node not bound to any document. There is no need of really including the node to\nthe document, but once the node is bound to a document, it is quite safe that all strings have\nthe correct encoding. If an unbound text node with an ISO encoded string is created (e.g. with\n$CLASS->new()), the \"toString\" function may not return the expected result.\n\nTo prevent such problems, it is recommended to pass all data to XML::LibXML methods as character\nstrings (i.e. UTF-8 encoded, with the UTF8 flag on).\n",
            "subsections": []
        },
        "METHODS": {
            "content": "Many functions listed here are extensively documented in the DOM Level 3 specification\n(<http://www.w3.org/TR/DOM-Level-3-Core/>). Please refer to the specification for extensive\ndocumentation.\n\nnew\n$dom = XML::LibXML::Document->new( $version, $encoding );\n\nalias for createDocument()\n\ncreateDocument\n$dom = XML::LibXML::Document->createDocument( $version, $encoding );\n\nThe constructor for the document class. As Parameter it takes the version string and\n(optionally) the encoding string. Simply calling *createDocument*() will create the\ndocument:\n\n<?xml version=\"your version\" encoding=\"your encoding\"?>\n\nBoth parameter are optional. The default value for *$version* is 1.0, of course. If the\n*$encoding* parameter is not set, the encoding will be left unset, which means UTF-8 is\nimplied.\n\nThe call of *createDocument*() without any parameter will result the following code:\n\n<?xml version=\"1.0\"?>\n\nAlternatively one can call this constructor directly from the XML::LibXML class level, to\navoid some typing. This will not have any effect on the class instance, which is always\nXML::LibXML::Document.\n\nmy $document = XML::LibXML->createDocument( \"1.0\", \"UTF-8\" );\n\nis therefore a shortcut for\n\nmy $document = XML::LibXML::Document->createDocument( \"1.0\", \"UTF-8\" );\n\nURI\n$strURI = $doc->URI();\n\nReturns the URI (or filename) of the original document. For documents obtained by parsing a\nstring of a FH without using the URI parsing argument of the corresponding \"parse*\"\nfunction, the result is a generated string unknown-XYZ where XYZ is some number; for\ndocuments created with the constructor \"new\", the URI is undefined.\n\nThe value can be modified by calling \"setURI\" method on the document node.\n\nsetURI\n$doc->setURI($strURI);\n\nSets the URI of the document reported by the method URI (see also the URI argument to the\nvarious \"parse*\" functions).\n\nencoding\n$strEncoding = $doc->encoding();\n\nreturns the encoding string of the document.\n\nmy $doc = XML::LibXML->createDocument( \"1.0\", \"ISO-8859-15\" );\nprint $doc->encoding; # prints ISO-8859-15\n\nactualEncoding\n$strEncoding = $doc->actualEncoding();\n\nreturns the encoding in which the XML will be returned by $doc->toString(). This is usually\nthe original encoding of the document as declared in the XML declaration and returned by\n$doc->encoding. If the original encoding is not known (e.g. if created in memory or parsed\nfrom a XML without a declared encoding), 'UTF-8' is returned.\n\nmy $doc = XML::LibXML->createDocument( \"1.0\", \"ISO-8859-15\" );\nprint $doc->encoding; # prints ISO-8859-15\n\nsetEncoding\n$doc->setEncoding($newencoding);\n\nThis method allows one to change the declaration of encoding in the XML declaration of the\ndocument. The value also affects the encoding in which the document is serialized to XML by\n$doc->toString(). Use setEncoding() to remove the encoding declaration.\n\nversion\n$strVersion = $doc->version();\n\nreturns the version string of the document\n\n*getVersion()* is an alternative form of this function.\n\nstandalone\n$doc->standalone\n\nThis function returns the Numerical value of a documents XML declarations standalone\nattribute. It returns *1* if standalone=\"yes\" was found, *0* if standalone=\"no\" was found\nand *-1* if standalone was not specified (default on creation).\n\nsetStandalone\n$doc->setStandalone($numvalue);\n\nThrough this method it is possible to alter the value of a documents standalone attribute.\nSet it to *1* to set standalone=\"yes\", to *0* to set standalone=\"no\" or set it to *-1* to\nremove the standalone attribute from the XML declaration.\n\ncompression\nmy $compression = $doc->compression;\n\nlibxml2 allows reading of documents directly from gzipped files. In this case the\ncompression variable is set to the compression level of that file (0-8). If XML::LibXML\nparsed a different source or the file wasn't compressed, the returned value will be *-1*.\n\nsetCompression\n$doc->setCompression($ziplevel);\n\nIf one intends to write the document directly to a file, it is possible to set the\ncompression level for a given document. This level can be in the range from 0 to 8. If\nXML::LibXML should not try to compress use *-1* (default).\n\nNote that this feature will *only* work if libxml2 is compiled with zlib support and\ntoFile() is used for output.\n\ntoString\n$docstring = $dom->toString($format);\n\n*toString* is a DOM serializing function, so the DOM Tree is serialized into an XML string,\nready for output.\n\nIMPORTANT: unlike toString for other nodes, on document nodes this function returns the XML\nas a byte string in the original encoding of the document (see the actualEncoding() method)!\nThis means you can simply do:\n\nopen my $outfh, '>', $file;\nprint {$outfh} $doc->toString;\n\nregardless of the actual encoding of the document. See the section on encodings in\nXML::LibXML for more details.\n\nThe optional *$format* parameter sets the indenting of the output. This parameter is\nexpected to be an \"integer\" value, that specifies that indentation should be used. The\nformat parameter can have three different values if it is used:\n\nIf $format is 0, than the document is dumped as it was originally parsed\n\nIf $format is 1, libxml2 will add ignorable white spaces, so the nodes content is easier to\nread. Existing text nodes will not be altered\n\nIf $format is 2 (or higher), libxml2 will act as $format == 1 but it add a leading and a\ntrailing line break to each text node.\n\nlibxml2 uses a hard-coded indentation of 2 space characters per indentation level. This\nvalue can not be altered on run-time.\n\ntoStringC14N\n$c14nstr = $doc->toStringC14N($commentflag, $xpath [, $xpathcontext ]);\n\nSee the documentation in XML::LibXML::Node.\n\ntoStringEC14N\n$ec14nstr = $doc->toStringEC14N($commentflag, $xpath [, $xpathcontext ], $inclusiveprefixlist);\n\nSee the documentation in XML::LibXML::Node.\n\nserialize\n$str = $doc->serialize($format);\n\nAn alias for toString(). This function was name added to be more consistent with libxml2.\n\nserializec14n\nAn alias for toStringC14N().\n\nserializeexcc14n\nAn alias for toStringEC14N().\n\ntoFile\n$state = $doc->toFile($filename, $format);\n\nThis function is similar to toString(), but it writes the document directly into a\nfilesystem. This function is very useful, if one needs to store large documents.\n\nThe format parameter has the same behaviour as in toString().\n\ntoFH\n$state = $doc->toFH($fh, $format);\n\nThis function is similar to toString(), but it writes the document directly to a filehandle\nor a stream. A byte stream in the document encoding is passed to the file handle. Do NOT\napply any \":encoding(...)\" or \":utf8\" PerlIO layer to the filehandle! See the section on\nencodings in XML::LibXML for more details.\n\nThe format parameter has the same behaviour as in toString().\n\ntoStringHTML\n$str = $document->toStringHTML();\n\n*toStringHTML* serialize the tree to a byte string in the document encoding as HTML. With\nthis method indenting is automatic and managed by libxml2 internally.\n\nserializehtml\n$str = $document->serializehtml();\n\nAn alias for toStringHTML().\n\nisvalid\n$bool = $dom->isvalid();\n\nReturns either TRUE or FALSE depending on whether the DOM Tree is a valid Document or not.\n\nYou may also pass in a XML::LibXML::Dtd object, to validate against an external DTD:\n\nif (!$dom->isvalid($dtd)) {\nwarn(\"document is not valid!\");\n}\n\nvalidate\n$dom->validate();\n\nThis is an exception throwing equivalent of isvalid. If the document is not valid it will\nthrow an exception containing the error. This allows you much better error reporting than\nsimply isvalid or not.\n\nAgain, you may pass in a DTD object\n\ndocumentElement\n$root = $dom->documentElement();\n\nReturns the root element of the Document. A document can have just one root element to\ncontain the documents data.\n\nOptionally one can use *getDocumentElement*.\n\nsetDocumentElement\n$dom->setDocumentElement( $root );\n\nThis function enables you to set the root element for a document. The function supports the\nimport of a node from a different document tree, but does not support a document fragment as\n$root.\n\ncreateElement\n$element = $dom->createElement( $nodename );\n\nThis function creates a new Element Node bound to the DOM with the name $nodename.\n\ncreateElementNS\n$element = $dom->createElementNS( $namespaceURI, $nodename );\n\nThis function creates a new Element Node bound to the DOM with the name $nodename and placed\nin the given namespace.\n\ncreateTextNode\n$text = $dom->createTextNode( $contenttext );\n\nAs an equivalent of *createElement*, but it creates a *Text Node* bound to the DOM.\n\ncreateComment\n$comment = $dom->createComment( $commenttext );\n\nAs an equivalent of *createElement*, but it creates a *Comment Node* bound to the DOM.\n\ncreateAttribute\n$attrnode = $doc->createAttribute($name [,$value]);\n\nCreates a new Attribute node.\n\ncreateAttributeNS\n$attrnode = $doc->createAttributeNS( namespaceURI, $name [,$value] );\n\nCreates an Attribute bound to a namespace.\n\ncreateDocumentFragment\n$fragment = $doc->createDocumentFragment();\n\nThis function creates a DocumentFragment.\n\ncreateCDATASection\n$cdata = $dom->createCDATASection( $cdatacontent );\n\nSimilar to createTextNode and createComment, this function creates a CDataSection bound to\nthe current DOM.\n\ncreateProcessingInstruction\nmy $pi = $doc->createProcessingInstruction( $target, $data );\n\ncreate a processing instruction node.\n\nSince this method is quite long one may use its short form *createPI()*.\n\ncreateEntityReference\nmy $entref = $doc->createEntityReference($refname);\n\nIf a document has a DTD specified, one can create entity references by using this function.\nIf one wants to add a entity reference to the document, this reference has to be created by\nthis function.\n\nAn entity reference is unique to a document and cannot be passed to other documents as other\nnodes can be passed.\n\n*NOTE:* A text content containing something that looks like an entity reference, will not be\nexpanded to a real entity reference unless it is a predefined entity\n\nmy $string = \"&foo;\";\n$someelement->appendText( $string );\nprint $someelement->textContent; # prints \"&amp;foo;\"\n\ncreateInternalSubset\n$dtd = $document->createInternalSubset( $rootnode, $public, $system);\n\nThis function creates and adds an internal subset to the given document. Because the\nfunction automatically adds the DTD to the document there is no need to add the created node\nexplicitly to the document.\n\nmy $document = XML::LibXML::Document->new();\nmy $dtd      = $document->createInternalSubset( \"foo\", undef, \"foo.dtd\" );\n\nwill result in the following XML document:\n\n<?xml version=\"1.0\"?>\n<!DOCTYPE foo SYSTEM \"foo.dtd\">\n\nBy setting the public parameter it is possible to set PUBLIC DTDs to a given document. So\n\nmy $document = XML::LibXML::Document->new();\nmy $dtd      = $document->createInternalSubset( \"foo\", \"-//FOO//DTD FOO 0.1//EN\", undef );\n\nwill cause the following declaration to be created on the document:\n\n<?xml version=\"1.0\"?>\n<!DOCTYPE foo PUBLIC \"-//FOO//DTD FOO 0.1//EN\">\n\ncreateExternalSubset\n$dtd = $document->createExternalSubset( $rootnodename, $publicId, $systemId);\n\nThis function is similar to \"createInternalSubset()\" but this DTD is considered to be\nexternal and is therefore not added to the document itself. Nevertheless it can be used for\nvalidation purposes.\n\nimportNode\n$document->importNode( $node );\n\nIf a node is not part of a document, it can be imported to another document. As specified in\nDOM Level 2 Specification the Node will not be altered or removed from its original document\n(\"$node->cloneNode(1)\" will get called implicitly).\n\n*NOTE:* Don't try to use importNode() to import sub-trees that contain an entity reference -\neven if the entity reference is the root node of the sub-tree. This will cause serious\nproblems to your program. This is a limitation of libxml2 and not of XML::LibXML itself.\n\nadoptNode\n$document->adoptNode( $node );\n\nIf a node is not part of a document, it can be imported to another document. As specified in\nDOM Level 3 Specification the Node will not be altered but it will removed from its original\ndocument.\n\nAfter a document adopted a node, the node, its attributes and all its descendants belong to\nthe new document. Because the node does not belong to the old document, it will be unlinked\nfrom its old location first.\n\n*NOTE:* Don't try to adoptNode() to import sub-trees that contain entity references - even\nif the entity reference is the root node of the sub-tree. This will cause serious problems\nto your program. This is a limitation of libxml2 and not of XML::LibXML itself.\n\nexternalSubset\nmy $dtd = $doc->externalSubset;\n\nIf a document has an external subset defined it will be returned by this function.\n\n*NOTE* Dtd nodes are no ordinary nodes in libxml2. The support for these nodes in\nXML::LibXML is still limited. In particular one may not want use common node function on\ndoctype declaration nodes!\n\ninternalSubset\nmy $dtd = $doc->internalSubset;\n\nIf a document has an internal subset defined it will be returned by this function.\n\n*NOTE* Dtd nodes are no ordinary nodes in libxml2. The support for these nodes in\nXML::LibXML is still limited. In particular one may not want use common node function on\ndoctype declaration nodes!\n\nsetExternalSubset\n$doc->setExternalSubset($dtd);\n\n*EXPERIMENTAL!*\n\nThis method sets a DTD node as an external subset of the given document.\n\nsetInternalSubset\n$doc->setInternalSubset($dtd);\n\n*EXPERIMENTAL!*\n\nThis method sets a DTD node as an internal subset of the given document.\n\nremoveExternalSubset\nmy $dtd = $doc->removeExternalSubset();\n\n*EXPERIMENTAL!*\n\nIf a document has an external subset defined it can be removed from the document by using\nthis function. The removed dtd node will be returned.\n\nremoveInternalSubset\nmy $dtd = $doc->removeInternalSubset();\n\n*EXPERIMENTAL!*\n\nIf a document has an internal subset defined it can be removed from the document by using\nthis function. The removed dtd node will be returned.\n\ngetElementsByTagName\nmy @nodelist = $doc->getElementsByTagName($tagname);\n\nImplements the DOM Level 2 function\n\nIn SCALAR context this function returns an XML::LibXML::NodeList object.\n\ngetElementsByTagNameNS\nmy @nodelist = $doc->getElementsByTagNameNS($nsURI,$tagname);\n\nImplements the DOM Level 2 function\n\nIn SCALAR context this function returns an XML::LibXML::NodeList object.\n\ngetElementsByLocalName\nmy @nodelist = $doc->getElementsByLocalName($localname);\n\nThis allows the fetching of all nodes from a given document with the given Localname.\n\nIn SCALAR context this function returns an XML::LibXML::NodeList object.\n\ngetElementById\nmy $node = $doc->getElementById($id);\n\nReturns the element that has an ID attribute with the given value. If no such element\nexists, this returns undef.\n\nNote: the ID of an element may change while manipulating the document. For documents with a\nDTD, the information about ID attributes is only available if DTD loading/validation has\nbeen requested. For HTML documents parsed with the HTML parser ID detection is done\nautomatically. In XML documents, all \"xml:id\" attributes are considered to be of type ID.\nYou can test ID-ness of an attribute node with $attr->isId().\n\nIn versions 1.59 and earlier this method was called getElementsById() (plural) by mistake.\nStarting from 1.60 this name is maintained as an alias only for backward compatibility.\n\nindexElements\n$dom->indexElements();\n\nThis function causes libxml2 to stamp all elements in a document with their document\nposition index which considerably speeds up XPath queries for large documents. It should\nonly be used with static documents that won't be further changed by any DOM methods, because\nonce a document is indexed, XPath will always prefer the index to other methods of\ndetermining the document order of nodes. XPath could therefore return improperly ordered\nnode-lists when applied on a document that has been changed after being indexed. It is of\ncourse possible to use this method to re-index a modified document before using it with\nXPath again. This function is not a part of the DOM specification.\n\nThis function returns number of elements indexed, -1 if error occurred, or -2 if this\nfeature is not available in the running libxml2.\n",
            "subsections": []
        },
        "AUTHORS": {
            "content": "Matt Sergeant, Christian Glahn, Petr Pajas\n",
            "subsections": []
        },
        "VERSION": {
            "content": "2.0134\n",
            "subsections": []
        },
        "COPYRIGHT": {
            "content": "2001-2007, AxKit.com Ltd.\n\n2002-2006, Christian Glahn.\n\n2006-2009, Petr Pajas.\n",
            "subsections": []
        },
        "LICENSE": {
            "content": "This program is free software; you can redistribute it and/or modify it under the same terms as\nPerl itself.\n",
            "subsections": []
        }
    },
    "summary": "XML::LibXML::Document - XML::LibXML DOM Document Class",
    "flags": [],
    "examples": [],
    "see_also": []
}