domNode(3tcl)
π domNode β the Tcl manual page, but make it a group chat β¨
okay so bestie, you're looking at domNode(3tcl), and this is the page that teaches you how to poke at one single DOM node object at a time. Sit down, hydrate, and let's get into it. π
β¨ NAME β¨
domNode β Manipulates an instance of a DOM node object π
πΈ SYNOPSIS πΈ
$nodeObject method arg arg ...
π DESCRIPTION π
So this command manipulates one particular instance of a DOM node object. The method bit is you picking a specific method of the node class. These methods should closely conform to the W3C recommendation "Document Object Model (Core) Level 1" (http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html) and also to parts of the W3C draft "XML Pointer Language (XPointer)" (http://www.w3.org/TR/1998/WD-xptr-19980303).
β οΈ Heads up bestie: the XPointer methods are deprecated. Use DOM methods or XPath expressions instead of them. Periodt. π
The selectNodes method implements the "XML Path Language (XPath) Version 1.0" W3C recommendation 16 November 1999 (http://www.w3.org/TR/1999/REC-xpath-19991116). Go read those documents if you want the deep lore on how this all actually works. π
The valid methods are:
nodeTypeβ Returns the node type of that node object. And it can be one of these:ELEMENT_NODE,TEXT_NODE,CDATA_SECTION_NODE,COMMENT_NODEorPROCESSING_INSTRUCTION_NODE. π·οΈnodeNameβ Returns the node name of that node object. So like: it's the element (tag) name for element nodes (typeELEMENT_NODE), the processing-instruction target for processing-instructions,"#text"for text node,"#comment"for comment nodes, or"#cdata"for cdata section nodes. β¨nodeValue ?newValue?β Returns the value of that node object. That's the text or the data for element nodes of typeTEXT_NODE,COMMENT_NODE,PROCESSING_INSTRUCTION_NODEorCDATA_SECTION_NODE. Otherwise it's empty. And if the node is aTEXT_NODE,COMMENT_NODEorPROCESSING_INSTRUCTION_NODEand you passed the optional argumentnewValue, then boom β the node is set to that value. π«ΆhasChildNodesβ Returns1if the node has children. Otherwise0comes back at you. Simple as. πparentNode ?objVar?β Returns the parent node.childNodesβ Returns a list of direct children node objects. π§childNodesLiveβ Returns a "live" nodeList object of the child nodes of the node, in the sense of the DOM recommendation. This nodeList object is "live" in the sense that, for instance, changes to the children of the node object that it was created from are immediately reflected in the nodes returned by the NodeList accessors β it is not a static snapshot of the content of the node. The two accessors known by the nodeList object areitem <index>, which returns the indexth item in the collection, andlength, which returns the number of nodes in the list. It's giving real-time. πfirstChild ?objVar?β Returns the first child as a node object.lastChild ?objVar?β Returns the last child as a node object.nextSibling ?objVar?β Returns the next sibling relative to the current node as a node object.previousSibling ?objVar?β Returns the next sibling relative to the current node as a node object.getElementsByTagName nameβ Returns a list of all elements in the subtree matching (glob style)name. πgetElementsByTagNameNS uri localnameβ Returns a list of all elements in the subtree matching (glob style)localnameand having the given namespaceuri.getElementById idβ Returns the node having anidattribute with valueid, or the empty string if no node has anidattribute with that value. No match, no drama. πhasAttribute attributeNameβ Returns1if the object node contains an attribute with nameattributeName. Otherwise0is returned.getAttribute attributeName ?defaultValue?β Returns the value of the attributeattributeName. If the attribute is not available,defaultValueis returned.setAttribute attributeName newValue ?attributeName newValue ...?β Sets the value for one or more attributes. EveryattributeNameis set to the correspondingnewValue. And if there isn't an attribute for one or more of theattributeNames, this will create that attribute. π οΈ
β οΈ It is not recommended to set attributes that look like XML namespace declarations. Just don't, bestie.
removeAttribute attributeNameβ Removes the attributeattributeName. Bye bye. πhasAttributeNS uri localNameβ Returns1if the object node contains an attribute with the local namelocalNamewithin the namespaceuri. Otherwise0is returned.getAttributeNS uri localName ?defaultValue?β Returns the value of the attribute with the local namelocalNamewithin the namespace URIuri. If the node dosn't have that attribute thedefaultValueis returned. πsetAttributeNS uri qualifiedName newValue ?uri qualifiedName newValue ...?β Sets the value for one or more full qualified attributes. Every attributequalifiedNamewith the namespace URIuriwill be set tonewValue. This will create a new attribute if it wasn't available before.
If you want to set an attribute within a namespace you must specify the attribute name with prefix, even if you want to set an already existing attribute to a new value. While searching, if the attribute already exists, only the given uri and the localname of the qualifiedName is used. iykyk. π
$node setAttributeNS "http://some.uri.com/wow" prefix:attr1 attrValue
If the uri is the empty string and the attribute name has no prefix, this method has the same effect as the method setAttribute.
$node setAttributeNS "" attri "some Value"
With the exceptions of the special prefixes "xmlns" and "xml" you always must provide a non empty uri if your qualifiedName has a prefix.
π¨ It is not recommended to set XML namespace declarations. The effects are complicated and not always obvious, up to resulting in a not well-formed serializations after further processing. Fr fr, don't do it. π
removeAttributeNS uri localNameβ Removes the attribute with the local namelocalNamewithin the namespaceuri.attributes ?attributeNamePattern?β Returns information about the attributes matching theattributeNamePattern. IfattributeNamePatternisn't given, information about all attributes are returned.
The return value is a Tcl list, the elements just the attribute name in case of non namespaced attributes, and three element sublists for namespaced attributes. In case of an "ordinary" namespaced attribute, the sublist elements are {<localname> <prefix> <namespace_uri>}. In the special case of an XML namespace declaration it is {<the prefix defined> <localname> ""}. π
attributeNames ?attributeNamePattern?β Returns a flat list of all attributes names (as found in the XML source) matching theattributeNamePattern. IfattributeNamePatternisn't given, all attribute names are returned as a Tcl list.appendChild newChildβ AppendsnewChildto the end of the child list of the node. βinsertBefore newChild refChildβ InsertsnewChildbefore therefChildinto the list of children of node. And ifrefChildis the empty string, insertnewChildat the end of the child nodes list of that node. Sneaky little shortcut, love that.replaceChild newChild oldChildβ ReplacesoldChildwithnewChildin the list of children of that node. TheoldChildnode will be part of the document fragment list after this operation. π¦removeChild childβ Removeschildfrom the list of children of that node.childwill be part of the document fragment list after this operation.deleteβ Deletes the given node and its complete child tree and frees the complete internal memory. The affected nodes are not accessible through the document fragment list. ποΈcloneNode ?-deep?β Clones this node and adds the new create node into the document fragment list. If the-deepoption is specified, all descendant nodes are also cloned. πownerDocument ?domObjVar?β Returns the document object of the document this node belongs to.find attrName attrVal ?objVar?β Finds the node with the attribute nameattrName, and attribute valueattrValin the subtree starting the current node.child number|all type attrName attrValueβ (XPointer) child. π§descendant number|all type attrName attrValueβ (XPointer) descendant.ancestor number|all type attrName attrValueβ (XPointer) ancestor.fsibling number|all type attrName attrValueβ (XPointer) fsibling.psibling number|all type attrName attrValueβ (XPointer) psibling.root objVarβ (XPointer) root.textβ Returns all text node children of that current node combined, i.e. appended into one string. One big string, no cap. π«Άtargetβ For a processing instruction node the target part is returned. Otherwise an error is generated. βdataβ For a processing instruction node the data part is returned. For a text node, comment node or cdata section node the value is returned. Otherwise an error is generated.prefixβ Returns the namespace prefix.namespaceURIβ Returns the namespace URI.localNameβ Returns thelocalNamefrom the tag name of the given node.selectNodes ?-namespaces prefixUriList? ?-cache <boolean>? ?-list? xpathQuery ?typeVar?andxpathQuery ?typeVar?β Returns the result of applying the XPath queryxpathQueryto the subtree. This result can be a string/value, a list of strings, a list of nodes or a list of attribute name / value pairs. If thetypeVarargument is given, the result type name is stored into that variable (and it'll be one ofempty,bool,number,string,nodes,attrnodesormixed). π
The argument xpathQuery has to be a valid XPath 1.0 expression. However there are a few exceptions to that rule. Tcl variable references (in the usual tcl syntax: $varname) may appear in the XPath statement at any position where it is legal according to the rules of the XPath syntax to put an XPath variable. And ignoring the syntax rules of XPath, the Tcl variable name may be any legal Tcl var name: local variables, global variables, array entries and so on. The value will always be seen as string literal by the xpath engine. Cast the value explicitly with the according xpath functions (number(), boolean()) to another data type, if needed. β¨
and that's part 1, bestie β more of this page is coming, don't go anywhere π
Okay so, same energy as injecting literals safely into your XPath with Tcl variable refs β there's also a syntax for injecting element names straight out of Tcl variables. Like, anywhere the XPath syntax lets a node test sit, you can drop a Tcl variable reference in (any form, bestie, any form), you just swap the leading $ for a %. And the reason this is lowkey iconic? It lets you select nodes with 'strange' names β the kind that are invalid according to the appropriate XML production rule β which you fr fr need when you're working with JSON data. π¦
The option -namespaces expects a Tcl list with prefix / namespace pairs as its argument. If you don't give this option, then any namespace prefix inside the xpath expression gets resolved first against the list of prefix / namespace pairs set with the selectNodesNamespaces method for the document that the node belongs to. If that fails, then the namespace definitions in scope of the context node get used to resolve the prefix. But if you do give this option, any namespace prefix within the xpath expression gets resolved first against that given list (and it just ignores the document global prefix / namespace list). If the list binds the same prefix to different namespaces, then the first binding wins. If this fails, then the namespace definitions in scope of the context node get used to resolve the prefix, as usual. β¨
If the -cache option is used with a true value, then the xpathQuery gets looked up in a document specific cache. Found it? Then the stored pre-compiled query gets used. Didn't find it? Then it gets compiled and stored in the cache, ready for further calls. π
Please note, bestie: the xpathQuery given as string is used as the key for the cache. Which means equal XPath expressions that differ only in white space are treated as different cache entries.
Special care is needed if the XPath expression includes namespace prefixes or references to Tcl variables. Both namespace prefixes and Tcl variable references get resolved according to the XML prefix namespace mappings and Tcl variable values at expression compilation time. So if the same XPath expression gets used later on in a context with other XML prefix namespace mappings or values of the used Tcl variables, make sure to first remove the compiled expression from the cache with the help of the deleteXPathCache method, to force a recompilation. Without using the -cache option such consideration is never needed. π
If the -list option is given then the xpathQuery argument is expected to be a Tcl list of XPath queries. Every XPath query in this list other than the last one must return a node set result. Using the context and namespace resolution rules as without the -list option, the first query out of the list is run. Every node out of the result set of this query is used as context node for the next XPath query out of the list and so on. It returns the result sets of the last query in the query list concatenated together. π
Examples:
set paragraphNodes [$node selectNodes {chapter[3]//para[@type='warning' or @type='error'} ]
foreach paragraph $paragraphNodes {
lappend values [$paragraph selectNodes attribute::type]
}
set doc [dom parse {<doc xmlns="http://www.defaultnamespace.org"><child/></doc>}]
set root [$doc documentElement]
set childNodes [$root selectNodes -namespaces {default http://www.defaultnamespace.org} default:child]
getLine
Returns the line number of that node in the originally parsed XML. The counting starts with 1. π
getColumn
Returns the column number of that node in the originally parsed XML. The counting starts with 0.
getByteIndex
Returns the byte position of that node in the originally parsed XML. The counting starts with 0.
asList
Returns the DOM substree starting from the current node as a nested Tcl list. πΈ
asXML
asXML ?-indent none/tabs/1..8? ?-channel channelId? ?-escapeNonASCII?
?-doctypeDeclaration <boolean>? -xmlDeclaration <boolean>? -encString
<string> ?-escapeAllQuot? ?-indentAttrs? ?-nogtescape?
?-noEmptyElementTag? ?-escapeCR? ?-escapeTab?
Returns the DOM substree starting from the current node as the root node of the result as an (optional indented) XML string, or sends the output directly to the given channelId. π«Ά
See the documentation of the
domDoc command method asXML for a detailed description of the arguments.
asCanonicalXML
asCanonicalXML ?-channel channelId? ?-comment?
Returns the DOM tree as canonical XML string according to the "Canonical XML Version 1.0 W3C Recommendation 15 March 2001", or sends the output directly to the given channelId.
See the documentation of the
domDoc command method asCanonicalXML for a detailed description of the arguments.
asHTML
asHTML ?-channel channelId? b?-escapeNonASCII? ?-htmlEntities?
?-doctypeDeclaration <boolean>? ?-breakLines? ?-onlyContents?
Returns the DOM substree starting from the current node as the root node of the result serialized according to HTML rules (HTML elements are recognized regardless of case, without end tags for empty HTML elements etc.), as string, or sends the output directly to the given channelId. π₯
See the documentation of the
domDoc method asHTML for a detailed description of the arguments.
asText
For ELEMENT_NODEs, the asText method outputs the string-value of every text node descendant of node in document order without any escaping. For every other node type, this method outputs the XPath string value of that node. β¨
asJSON
asJSON ?-indent none/0..8? ?-channel channelId?
The asJSON method serializes the subtree starting with the node the method was called on into a valid JSON data string. π
See the documentation of the
domDoc method asJSON for a detailed description of the method
asTclValue
asTclValue ?typevariable?
In case the subtree starting with the node the method was called on includes JSON type information, this method returns the JSON data as nested Tcl data structure.
See the documentation of the
domDoc method asTclValue for a detailed description of the method
appendFromList
appendFromList list
Parses list, creates an according DOM subtree, and appends this subtree to the current node. π
appendFromScript
appendFromScript tclScript
Appends the nodes created in the tclScript by Tcl functions, which have been built using dom createNodeCmd, to the given node.
insertBeforeFromScript
insertBeforeFromScript tclScript refChild
Inserts the nodes created in the tclScript by Tcl functions, which have been built using dom createNodeCmd, before the refChild into the list of children of node. If refChild is the empty string, the new nodes will be appended. π
appendXML
appendXML XMLstring
Parses XMLstring, creates an according DOM subtree, and appends this subtree to the current node.
simpleTranslate
simpleTranslate outputVar specifications
Translates the subtree starting at the object node according to the specifications in specifications and outputs the result in the variable outputVar. The translation is very similar to Cost Simple mode. π¦
toXPath
toXPath ?-legacy?
Returns an XPath which exactly addresses the given node in its document. This XPath is only valid as there are no changes to DOM tree made later one. With the -legacy option, other XPath expressions are returned, which doesn't work in all cases. β οΈ
getBaseURI
Returns the baseURI of the node. This method is deprecated in favor of the baseURI method. π
baseURI
baseURI ?URI?
Returns the present baseURI of the node. If the optional argument URI is given, it sets the base URI of the node and of all of its child nodes out of the same entity as node to the given URI.
disableOutputEscaping
disableOutputEscaping ?boolean?
This method works only for text nodes; for every other node it returns error. Without the optional argument it returns whether disabling output escaping is on. The return value 0 means the characters of the text node will be escaped, to generate valid XML, if serialized. This is the default for every parsed or created text node (with the exception of those text nodes in a result tree of an XSLT transformation, for which disabling output escaping was requested explicitly in the stylesheet). The return value 1 means that output escaping is disabled for this text node. If such a text node is serialized (with asXML or asHTML), it is literally written, without escaping of the special XML characters. If the optional boolean value boolean is given, the flag is set accordingly.
You should not set this flag to 1 until you really know what you do, bestie. π
precedes
precedes refnode
Compares the relative order of the node and refnode. Both nodes must be part of the same documents and not out of the fragment list of the document. Returns true if node is in document order (in the sense of the XPath 1.0 recommendation) before refnode, and false otherwise.
normalize
normalize ?-forXPath?
Puts all Text nodes in the full depth of the sub-tree underneath this Node into a "normal" form where only structure (e.g., elements, comments, processing instructions and CDATA sections) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes. If the option -forXPath is given, all CDATA sections in the nodes are converted to text nodes, as a first step before the normalization. β¨
xslt
xslt ?-parameters parameterList? ?-ignoreUndeclaredParameters?
?-maxApplyDepth int? ?-xsltmessagecmd script? stylesheet ?outputVar?
Applies an XSLT transformation on the document using the XSLT stylesheet (given as domDoc). Returns a document object containing the result document of that transformation and stores it in the optional outputVar. π
The optional -parameters option sets top level <xsl:param> to string values. The parameterList has to be a Tcl list consisting of parameter name and value pairs.
Ok so lowkey the options era is still going, bestie, we're almost there, stay with me π
-ignoreUndeclaredParametersβ when you pass this, any parameter name sitting in theparameterListyou handed to the-parametersoptions that isn't declared as a top-level parameter in the stylesheet justβ¦ gets silently yeeted into the void. No drama. But if you don't give this option and you try to set a top-level parameter that the stylesheet never declared? Boom, error. π-maxApplyDepthβ this one wants a positive integer, no negotiation. Out of the box the XSLT engine lets XSLT templates nest up to 3000 levels deep (and raises an error if they go any deeper, like, calm down). This limit is settable via-maxApplyDepth. π«Ά-xsltmessagecmdβ sets up a callback forxslt:messageelements in the stylesheet. The actual command you get is the script (that's the argument you gave the option) with two things glued onto it:- the XML Fragment that comes from instantiating the
xsl:messageelement's content as a string (as if the XPathstring()function had been applied to that XML Fragment) - a flag that says whether the
xsl:messagehas an attribute"terminate"with the value"yes"
- the XML Fragment that comes from instantiating the
If the called script returns anything other than TCL_OK, the XSLT transformation gets aborted and an error comes back. If the called script returns -code break, the error message is empty; otherwise the result code gets reported. And if the transformation got terminated, the outputVar β assuming you gave one β is set to the empty string. Noted, fr fr. β¨
πΈ the methods that are just vibing here πΈ
@attrNameβ hands you back the value of the attribute attrName. It's literally just a shortcut forgetAttribute, iykyk. πjsonType ?(OBJECT|ARRAY|NONE)|(STRING|NUMBER|TRUE|FALSE|NULL|NONE)?β okay so only element and text nodes are allowed to have a JSON type, and only these node types even support thejsonTypemethod. Every other node type will just return an error if you call this on it, no cap. π
What you get back is the node's jsonType. But if you hand it the optional argument, the node's JSON type gets set to the type you gave and then returned to you. The valid type arguments break down like this:
- element nodes:
OBJECT,ARRAY,NONE - text nodes:
STRING,NUMBER,TRUE,FALSE,NULL,NONE
Otherwise β like, if you throw some totally unknown method name at it β the command with that same name inside the namespace ::dom::domNode gets tried instead. That's the whole trick: it lets you add methods quick on the Tcl level. Iconic behavior honestly. π
β¨ SEE ALSO β¨
domdomDoc
π KEYWORDS π
XMLDOMdocumentnodeparsing
okay that's the whole page, you made it, I'm so proud of you π This beauty comes to you from the Tcl crew as domNode(3tcl) β section 3tcl energy, dated and versioned the way man pages always are. Go forth and parse, bestie. slay β¨
π¦ where this page comes from
- ubuntu resolute: tdom 0.9.6-2 Β· MPL-2.0
- ubuntu stonking: tdom 0.9.6-3 Β· MPL-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms