XML::LibXML::Node(3)
XML::LibXML::Node π
User Contributed Perl Documentation Β· XML::LibXML::Node(3)
okay bestie, sit down, hydrate, because this is the abstract base class of every single XML::LibXML node type and she is foundational. π
β¨ NAME β¨
XML::LibXML::Node β the abstract base class of XML::LibXML nodes. Like, the mother of all nodes. The blueprint. The blueprint that says "you will have a nodeName and you WILL like it". π
πΈ SYNOPSIS πΈ
use XML::LibXML;
$name = $node->nodeName;
$node->setNodeName( $newName );
$bool = $node->isSameNode( $other_node );
$bool = $node->isEqual( $other_node );
$num = $node->unique_key;
$content = $node->nodeValue;
$content = $node->textContent;
$type = $node->nodeType;
$node->unbindNode();
$childnode = $node->removeChild( $childnode );
$oldnode = $node->replaceChild( $newNode, $oldNode );
$node->replaceNode($newNode);
$childnode = $node->appendChild( $childnode );
$childnode = $node->addChild( $childnode );
$node = $parent->addNewChild( $nsURI, $name );
$node->addSibling($newNode);
$newnode =$node->cloneNode( $deep );
$parentnode = $node->parentNode;
$nextnode = $node->nextSibling();
$nextnode = $node->nextNonBlankSibling();
$prevnode = $node->previousSibling();
$prevnode = $node->previousNonBlankSibling();
$boolean = $node->hasChildNodes();
$childnode = $node->firstChild;
$childnode = $node->lastChild;
$documentnode = $node->ownerDocument;
$node = $node->getOwner;
$node->setOwnerDocument( $doc );
$node->insertBefore( $newNode, $refNode );
$node->insertAfter( $newNode, $refNode );
@nodes = $node->findnodes( $xpath_expression );
$result = $node->find( $xpath_expression );
print $node->findvalue( $xpath_expression );
$bool = $node->exists( $xpath_expression );
@childnodes = $node->childNodes();
@childnodes = $node->nonBlankChildNodes();
$xmlstring = $node->toString($format,$docencoding);
$c14nstring = $node->toStringC14N();
$c14nstring = $node->toStringC14N($with_comments, $xpath_expression , $xpath_context);
$c14nstring = $node->toStringC14N_v1_1();
$c14nstring = $node->toStringC14N_v1_1($with_comments, $xpath_expression , $xpath_context);
$ec14nstring = $node->toStringEC14N();
$ec14nstring = $node->toStringEC14N($with_comments, $xpath_expression, $inclusive_prefix_list);
$ec14nstring = $node->toStringEC14N($with_comments, $xpath_expression, $xpath_context, $inclusive_prefix_list);
$str = $doc->serialize($format);
$localname = $node->localname;
$nameprefix = $node->prefix;
$uri = $node->namespaceURI();
$boolean = $node->hasAttributes();
@attributelist = $node->attributes();
$URI = $node->lookupNamespaceURI( $prefix );
$prefix = $node->lookupNamespacePrefix( $URI );
$node->normalize;
@nslist = $node->getNamespaces;
$node->removeChildNodes();
$strURI = $node->baseURI();
$node->setBaseURI($strURI);
$node->nodePath();
$lineno = $node->line_number();
π DESCRIPTION π
XML::LibXML::Node is where all the functions live that every node type needs. She's the shared brain cell, bestie.
π¨ IMPORTANT: you should never create anXML::LibXML::Nodestandalone. She's abstract. You get her as an instance of a high-level class likeXML::LibXML::ElementorXML::LibXML::Text. She only provides common functionality β that's her whole thing.
In XML::LibXML, every node is part of either a document or a document-fragment. Which means: there is no node without a parent. Periodt. π«Ά
That's why "unbound" nodes get confusing β because technically nothing is ever fully parentless, the unbound ones just get tucked away somewhere you can't see. π
π₯ METHODS π₯
A bunch of these are documented in great detail in the DOM Level 3 specification (<http://www.w3.org/TR/DOM-Level-3-Core/>). Go read the spec if you want the extended cut. π
π¦ nodeName
$name = $node->nodeName;
Returns the node's name. This one is namespace-aware and hands you the full name of the current node, like "prefix:localname".
Since 1.62, she also returns the correct DOM names for node types that have constant names, specifically: #text, #cdata-section, #comment, #document, #document-fragment. slay. β¨
π¦ setNodeName
$node->setNodeName( $newName );
In very limited situations it's useful to rename a node. In the DOM spec this should throw an error, but here we are. This function is namespace-aware. π
π¦ isSameNode
$bool = $node->isSameNode( $other_node );
Returns TRUE (1) if the two nodes refer to the same node structure. Otherwise FALSE (0). Simple as that, no cap. π«Ά
π¦ isEqual
$bool = $node->isEqual( $other_node );
Deprecated version of isSameNode().
β οΈ NOTE: isEqual will change behaviour to follow the DOM specification. So don't get attached to the current vibe, bestie, she's getting a glow-up and it might not be the one you wanted. π
π¦ unique_key
$num = $node->unique_key;
Not specified for any DOM level β she's a homegrown icon. π
Returns a key that's guaranteed to be unique for this node, and to always be the same value for this node. In other words: two node objects return the same key if and only if isSameNode says they're the same node.
The returned key value is useful as a key in hashes. hash girlies rise. π
π¦ nodeValue
$content = $node->nodeValue;
If the node has any content (like, the stuff stored in a "text node") you can grab it through this function.
β οΈ NOTE: Element Nodes have no content per definition. If you want the text value of an Element, usetextContent()instead! Don't come crying to me whennodeValuegives you nothing. π
π¦ textContent
$content = $node->textContent;
Returns the content of all the text nodes in the descendants of the given node, exactly as specified in DOM. This is the one you actually want for elements, bestie. π
π¦ nodeType
$type = $node->nodeType;
Returns a numeric value representing the node type of this node. The module XML::LibXML by default exports constants for the node types β see the EXPORT section in the XML::LibXML manual page. π
π¦ unbindNode
$node->unbindNode();
Unbinds the node from its siblings and parent β but not from the document it belongs to. If the node isn't inserted back into the DOM afterwards, it will be lost after the program terminates. π
From a low-level view: the unbound node gets stripped from the context it's in and inserted into a (hidden) document-fragment. It's giving "moved out but still on the family phone plan". π
π¦ removeChild
$childnode = $node->removeChild( $childnode );
Unbinds the child node from its parent $node. The function returns the unbound node. If $childnode is not a child of the given Node, the function will fail. Vibe check: failed. π
π¦ replaceChild
$oldnode = $node->replaceChild( $newNode, $oldNode );
Replaces $oldNode with $newNode. The $oldNode gets unbound from the Node. β¨
This function differs from the DOM L2 specification: if the new node isn't part of the document, the node will be imported first. So she does the paperwork for you. π«Ά
π¦ replaceNode
$node->replaceNode($newNode);
Very similar to replaceChild(), but it replaces the node itself rather than a childnode. Super useful when a node was found by some XPath function and you wanna swap her out. π₯
π¦ appendChild
$childnode = $node->appendChild( $childnode );
Adds $childnode to the end of $node's children. The function should fail if the new childnode is already a child of $node.
This function differs from the DOM L2 specification: if the new node isn't part of the document, the node will be imported first. Again: she does the paperwork. π
π¦ addChild
$childnode = $node->addChild( $childnode );
The alternative to appendChild(). She's a bit faster because she skips all the DOM conformity checks. So she's genuinely useful when you're building XML documents in memory, where the order and ownership ("ownerDocument") are already assured. main character efficiency. β‘
addChild() uses libxml2's own xmlAddChild() function. So use her with extra care:
If a text node is added to a node and the node itself or its last childnode is also a text node, the node you're adding will be merged with the one already there. The current node gets removed from memory after this action. Because perl has no idea this happened, the perl instance is still sitting there like nothing's wrong. XML::LibXML will catch the loss of a node and refuse to run any function called on that node.
my $t1 = $doc->createTextNode( "foo" );
my $t2 = $doc->createTextNode( "bar" );
$t1->addChild( $t2 ); # is OK
my $val = $t2->nodeValue(); # will fail, script dies
Also, addChild() will not check whether the added node belongs to the same document as the node she's being added to. That can lead to inconsistent documents, and in worse cases even to memory violations if you're not keeping track of this. π
Even though that sounds like a lot of trouble, addChild() is useful when a document is built from a stream β like what happens sometimes in SAX handlers or filters.
If you're not sure about the source of your nodes, you better stay with appendChild(), because that one is more user friendly in the sense of being more error tolerant. π«Ά
π¦ addNewChild
$node = $parent->addNewChild( $nsURI, $name );
Similar to addChild(), this uses low-level libxml2 functionality to give you a faster interface for DOM building. addNewChild() uses xmlNewChild() to create a new node on a given parent element.
She takes two parameters: $nsURI and $name, where $nsURI is an (optional) namespace URI. $name is the fully qualified element name β addNewChild() will figure out the correct prefix if necessary. Iconic of her honestly. π
Returns the newly created node.
Super useful for DOM building, where a created node can be directly associated with its parent.
β οΈ NOTE: this function is not part of the DOM specification, and using her will limit your code to XML::LibXML. iykyk. π
π¦ addSibling
$node->addSibling($newNode);
Lets you add an additional node to the end of a nodelist, defined by the given node. π
π¦ cloneNode
$newnode =$node->cloneNode( $deep );
Creates a copy of $node. When $deep is set to 1 (true), she copies all the child nodes too. If $deep is 0, only the current node gets copied. Note that in the case of an element, attributes are copied even if $deep is 0.
β οΈ Note: the behaviour of this function for $deep=0 changed in 1.62 to be consistent with the DOM spec. In older versions, attributes and namespace information were not copied for elements. so if you're on an old version, act accordingly. π
β οΈ NOTE: cloneNode creates a copy of the selected node that includes the parent's defined namespaces that are in use by the node (or its children) being cloned. That makes her useful for extracting a fragment of xml that can be used as a valid xml document. β¨
π¦ parentNode
$parentnode = $node->parentNode;
Returns simply the parent node of the current node. No drama, no lore. π«Ά
π¦ nextSibling
$nextnode = $node->nextSibling();
So the next sibling? If there is one, nextSibling hands it right over. If there isn't, you get nothing. That's the whole vibe. π
nextNonBlankSibling
$nextnode = $node->nextNonBlankSibling();
Gives you the next non-blank sibling, if any. And bestie, "blank" has a very specific meaning here: a node is blank if it's a Text or CDATA node made up of whitespace only. No real content, no vibes. π«₯
Heads up: this method is not defined by DOM.
previousSibling
$prevnode = $node->previousSibling();
Same energy as getNextSibling, except it walks backwards β it returns the previous sibling, if any. βͺ
previousNonBlankSibling
$prevnode = $node->previousNonBlankSibling();
Returns the previous non-blank sibling, if any (same blankness rule: a Text or CDATA node that's nothing but whitespace counts as blank).
Again: this method is not defined by DOM.
hasChildNodes
$boolean = $node->hasChildNodes();
Does this node have child nodes? Then you get TRUE (1). It doesn't? You get FALSE β and listen, it's 0, not undef. Very important distinction, don't let anyone lie to you. π€
firstChild
$childnode = $node->firstChild;
If a node has children, this hands you the first one in the child list. First in line, main character. π
lastChild
$childnode = $node->lastChild;
If $node has child nodes, this one gives you the last child node. Closing the lineup. π¬
ownerDocument
$documentnode = $node->ownerDocument;
Through this function you can always get to the document that the current node is bound to. Always. No cap. π
getOwner
$node = $node->getOwner;
Returns the node the current node is associated with. Most of the time that's gonna be a document node or a document fragment node. π
setOwnerDocument
$node->setOwnerDocument( $doc );
This binds a node to a different DOM. And if the node was already bound to another document, it gets unbound first. Out with the old, in with the new. β¨
This function is the exact opposite of calling XML::LibXML::Document's adoptNode() function. And because of that, it comes with the same limitations with Entity References as adoptNode() does.
insertBefore
$node->insertBefore( $newNode, $refNode );
Inserts $newNode before $refNode. If $refNode is undefined, then $newNode gets set as the new last child of the parent node.
This function differs from the DOM L2 specification in one case: if the new node isn't part of the document, the node gets imported first, automatically. πͺ
$refNode has to be passed to the function even if it's undefined:
$node->insertBefore( $newNode, undef ); # the same as $node->appendChild( $newNode );
$node->insertBefore( $newNode ); # wrong
Note, note, NOTE π’ β the reference node has to be a direct child of the node the function is called on. Also, $newChild is not allowed to be an ancestor of the new parent node.
insertAfter
$node->insertAfter( $newNode, $refNode );
Inserts $newNode after $refNode. If $refNode is undefined, $newNode becomes the new last child of the parent node. π
Note that$refNodehas to be passed explicitly, even if it'sundef.
findnodes
@nodes = $node->findnodes( $xpath_expression );
findnodes evaluates the xpath expression (XPath 1.0) on the current node and returns the resulting node set as an array. In scalar context? You get an XML::LibXML::NodeList object instead. πΈ
The xpath expression can be passed either as a string, or as an XML::LibXML::XPathExpression object.
NOTE ON NAMESPACES AND XPATH:
A super common mistake about XPath is assuming that node tests made of an element name with no prefix will match elements in the default namespace. Nope, that assumption is wrong β by XPath specification, those node tests can only match elements that are in no (i.e. null) namespace. π
So for example, you cannot match the root element of an XHTML document with $node->find('/html'), because /html would only match if the root element <html> had no namespace β but all XHTML elements belong to the namespace http://www.w3.org/1999/xhtml. (And note that xmlns="..." namespace declarations can also be specified in a DTD, which makes everything even worse, since the XML document then looks like there's no default namespace at all. π)
There are several possible ways to deal with namespaces in XPath:
- The recommended way is to use the
XML::LibXML::XPathContextmodule to define an explicit context for XPath evaluation, where you can define a document-independent prefix-to-namespace mapping. For example:
my $xpc = XML::LibXML::XPathContext->new;
$xpc->registerNs('x', 'http://www.w3.org/1999/xhtml');
$xpc->find('/x:html',$node);
- Another possibility is to use prefixes declared in the queried document (if they're known). If the document declares a prefix for the namespace in question (and the context node is in the scope of that declaration),
XML::LibXMLlets you use the prefix in the XPath expression, like:
$node->find('/x:html');
See also XML::LibXML::XPathContext->findnodes.
find
$result = $node->find( $xpath_expression );
find evaluates the XPath 1.0 expression using the current node as the context of the expression, and returns a result depending on what type of result the XPath expression had. Like, the XPath 1 * 3 + 52 results in an XML::LibXML::Number object being returned. Other expressions might return an XML::LibXML::Boolean object, or an XML::LibXML::Literal object (a string). Each of those objects uses Perl's overload feature to "do the right thing" in different contexts. β¨
The xpath expression can be passed either as a string, or as an XML::LibXML::XPathExpression object.
See also XML::LibXML::XPathContext->find.
findvalue
print $node->findvalue( $xpath_expression );
findvalue is exactly equivalent to:
$node->find( $xpath_expression )->to_literal;
That is, it returns the literal value of the results. This lets you make sure you get a string back from your search, which allows certain shortcuts. Think of it as the equivalent of XSLT's <xsl:value-of select="some_xpath"/>. π
See also XML::LibXML::XPathContext->findvalue.
The xpath expression can be passed either as a string, or as an XML::LibXML::XPathExpression object.
exists
$bool = $node->exists( $xpath_expression );
This method behaves like findnodes, except it only returns a boolean value (1 if the expression matches a node, 0 otherwise). And it may be faster than findnodes, because the XPath evaluation may stop early on the first match (this is true for libxml2 >= 2.6.27). π₯
For XPath expressions that do not return node-set, the method returns true if the returned value is a non-zero number or a non-empty string.
childNodes
@childnodes = $node->childNodes();
childNodes implements a much more intuitive interface to the childnodes of the current node. It lets you pass all the children directly to a map or grep. And if this function is called in scalar context, an XML::LibXML::NodeList object gets returned. π¦
nonBlankChildNodes
@childnodes = $node->nonBlankChildNodes();
This is like childNodes, but it returns only non-blank nodes (where a node is blank if it's a Text or CDATA node consisting of whitespace only).
This method is not defined by DOM.
toString
$xmlstring = $node->toString($format,$docencoding);
This method is similar to the toString method of an XML::LibXML::Document, but for a single node. It returns a string consisting of the XML serialization of the given node and all its descendants.
Unlike XML::LibXML::Document::toString, in this case the resulting string is by default a character string (UTF-8 encoded with the UTF8 flag on). π§ An optional flag $format controls indentation, just like in XML::LibXML::Document::toString. And if the second optional $docencoding flag is true, the result will be a byte string in the document encoding (see XML::LibXML::Document::actualEncoding).
toStringC14N
$c14nstring = $node->toStringC14N();
$c14nstring = $node->toStringC14N($with_comments, $xpath_expression , $xpath_context);
This function is similar to toString(). But instead of just serializing the document tree, it transforms it as specified in the XML-C14N Specification (see <http://www.w3.org/TR/xml-c14n>). That kind of transformation is known as canonization. β
If $with_comments is 0 or not defined, the result-document will not contain any comments that exist in the original document. To include comments in the canonized document, $with_comments has to be set to 1.
The parameter $xpath_expression defines the nodeset of nodes that should be visible in the resulting document. This can be used to filter out some nodes. One thing you have to note: only the nodes that are part of the nodeset will be included in the result-document. Their child-nodes will not exist in the resulting document, unless they are part of the nodeset defined by the xpath expression.
If $xpath_expression is omitted or empty, toStringC14N() will include all nodes in the given sub-tree, using the following XPath expressions:
with comments
(. | .//node() | .//@* | .//namespace::*)
and without comments
(. | .//node() | .//@* | .//namespace::*)[not(self::comment())]
An optional parameter $xpath_context can be used to pass an XML::LibXML::XPathContext object defining the context for evaluation of $xpath_expression. This is useful for mapping namespace prefixes used in the XPath expression to namespace URIs. However β note that $node will be used as the context node for the evaluation, not the context node of $xpath_context! π«Ά
toStringC14N_v1_1
$c14nstring = $node->toStringC14N_v1_1();
$c14nstring = $node->toStringC14N_v1_1($with_comments, $xpath_expression , $xpath_context);
This function behaves exactly like toStringC14N(), except it uses the XML_C14N_1_1 constant for canonicalising using the C14N 1.1 spec. π
toStringEC14N
$ec14nstring = $node->toStringEC14N();
$ec14nstring = $node->toStringEC14N($with_comments, $xpath_expression, $inclusive_prefix_list);
$ec14nstring = $node->toStringEC14N($with_comments, $xpath_expression, $xpath_context, $inclusive_prefix_list);
This function is similar to toStringC14N() but follows the XML-EXC-C14N Specification (see <http://www.w3.org/TR/xml-exc-c14n>) for exclusive canonization of XML. π
The args $with_comments, $xpath_expression, and $xpath_context work exactly like they do in toStringC14N(), bestie π. And you can slide an ARRAY reference in as that last arg, $inclusive_prefix_list β it's a lil list of namespace prefixes that get handled the way the Canonical XML Recommendation says (aka they're kept in the output even if nothing actually uses that namespace). C.f. the spec if you want the full tea β.
serialize
$str = $doc->serialize($format);
Just an alias for toString(). It got this name so it vibes harder with libxml2. That's it, that's the whole thing β¨
serialize_c14n
An alias for toStringC14N().
serialize_exc_c14n
An alias for toStringEC14N().
localname
$localname = $node->localname;
Gives you the local name of a tag β the bit behind the colon π
prefix
$nameprefix = $node->prefix;
Gives you the prefix of a tag β the bit before the colon π«Ά
namespaceURI
$uri = $node->namespaceURI();
Returns the URI of whatever namespace you're currently in π
hasAttributes
$boolean = $node->hasAttributes();
Returns 1 (TRUE) if the current node has any attributes set on it, otherwise you get 0 (FALSE). Simple as π
attributes
@attributelist = $node->attributes();
This one hands you back every attribute and namespace declaration that's assigned to the node you're looking at.
Now, heads up bestie: because XML::LibXML doesn't implement namespace declarations and attributes the same way, you gotta check what kind of node you're dealing with before you go poking at the result π.
- In array context β the attribute nodes come back as an array.
- In scalar context β you get an
XML::LibXML::NamedNodeMapobject instead.
lookupNamespaceURI
$URI = $node->lookupNamespaceURI( $prefix );
Finds a namespace URI by its prefix, starting from the current node πΈ
lookupNamespacePrefix
$prefix = $node->lookupNamespacePrefix( $URI );
Finds a namespace prefix by its URI, starting from the current node.
NOTE: Only the namespace URIs are meant to be unique. The prefix is only document-related, fr fr. Also, a single document might have more than one prefix defined for the same namespace. No cap π
normalize
$node->normalize;
This one normalizes adjacent text nodes. It's not as strict as libxml2's xmlTextMerge() function though β because it will not free a node that's still being referenced by the perl layer. Safety first, bestie π
getNamespaces
@nslist = $node->getNamespaces;
If a node has any namespaces defined, this hands them over. But note: this does not return all the namespaces that are in scope β only the ones explicitly declared for that specific node π
And even though getNamespaces is available for all nodes, it only actually makes sense if you use it on element nodes. Periodt.
removeChildNodes
$node->removeChildNodes();
This function isn't specified for any DOM level: it removes all childnodes from a node in one single step π₯. But unlike the libxml2 function itself (xmlFreeNodeList), it will not immediately remove the nodes from memory. Which is actually a slay, because it saves you from getting memory violations if there are nodes still being referred to from the Perl level π
baseURI ()
$strURI = $node->baseURI();
Searches for the base URL of the node π. The method should work on both XML and HTML documents β even though the base mechanisms for those two are completely different. It returns the base as defined in RFC 2396 sections "5.1.1. Base URI within Document Content" and "5.1.2. Base URI from the Encapsulating Entity".
But β and this is the important bit β it does not return the document base (5.1.3). For that, go use the URI method of XML::LibXML::Document instead. Different function, different job, iykyk π
setBaseURI ($strURI)
$node->setBaseURI($strURI);
This method only does something useful for an element node in an XML document. It sets the xml:base attribute on the node to $strURI, which effectively sets the base URI of the node to that same value β¨
Note: For HTML documents this behaves as if the document was XML β which may not be what you want, since it does not effectively set the base URI of the node. Check RFC 2396 appendix D for an example of how base URI can be specified in HTML.
nodePath
$node->nodePath();
Not specified for any DOM level: it returns a canonical structure based XPath for a given node π¦
line_number
$lineno = $node->line_number();
Returns the line number where the tag was found during parsing π. If a node gets added to the document, the line number is 0. Problems may occur if a node from one document is passed to another one. Messy.
IMPORTANT: Due to limitations in the libxml2 library, line numbers greater than65535will be returned as65535. Please seehttp://bugzilla.gnome.org/show_bug.cgi?id=325533for more details. π
Note: line_number() is special to XML::LibXML and is not part of the DOM specification.
And if the line_numbers flag of the parser wasn't activated before parsing, line_number() will always return 0. Forever. Zero. π«
π AUTHORS π
Matt Sergeant, Christian Glahn, Petr Pajas π
β 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 π
okay bestie that's a wrap on XML::LibXML::Node(3) π«Ά this beauty is perl v5.42.2, dated 2026-05-25, and honestly? iconic. go forth and slay your XML π
β¨
π¦ 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