domNode(n)
π NAME π
domNode β manipulates an instance of a DOM node object π¦
π SYNOPSIS π
$nodeObject method arg arg ...
β¨ DESCRIPTION β¨
okay so bestie, this command manipulates one particular instance of a DOM node object. method tells it which specific method of the node class you want. 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. fr fr.
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). Look at these documents for a deeper understanding of the functionality. iykyk π
The valid methods are:
π the valid methods π
nodeTypeβ returns the node type of that node object. This can be:ELEMENT_NODE,TEXT_NODE,CDATA_SECTION_NODE,COMMENT_NODEorPROCESSING_INSTRUCTION_NODE.nodeNameβ returns the node name of that node object. For element nodes (typeELEMENT_NODE) this is the element (tag) name, for processing-instructions it's the processing-instruction target,#textfor text node,#commentfor comment nodes or#cdatafor cdata section nodes.nodeValue ?newValue?β returns the value of that node object. This is the text or the data for element nodes of typeTEXT_NODE,COMMENT_NODE,PROCESSING_INSTRUCTION_NODEorCDATA_SECTION_NODE. Otherwise it is empty. If the node is aTEXT_NODE,COMMENT_NODEorPROCESSING_INSTRUCTION_NODEand the optional argumentnewValueis given, the node is set to that value. β¨hasChildNodesβ returns1if the node has children. Otherwise0is returned.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.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. π yes it says next sibling here too, that's literally what the page says, I'm just the messenger bestie.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 valueidor the empty string if no node has anidattribute with that value.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 availabledefaultValueis returned.setAttribute attributeName newValue ?attributeName newValue ...?β sets the value for one or more attributes. EveryattributeNameis set to the correspondingnewValue. If there isn't an attribute for one or more of theattributeName, this will create that attribute.
β οΈ it is not recommended to set attributes that look like XML namespace declarations. don't do it bestie.
removeAttribute attributeNameβ removes the attributeattributeName.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 givenuriand the localname of thequalifiedNameis used.
$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 a not well-formed serializations after further processing. π seriously, chaos energy.
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. IfrefChildis the empty string, insertnewChildat the end of the child nodes list of that node.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. π gone gone.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) childdescendant number|all type attrName attrValueβ (XPointer) descendantancestor number|all type attrName attrValueβ (XPointer) ancestorfsibling number|all type attrName attrValueβ (XPointer) fsiblingpsibling number|all type attrName attrValueβ (XPointer) psiblingroot objVarβ (XPointer) roottextβ returns all text node children of that current node combined, i.e. appended into one string.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 the localName from the tag name of the given node.selectNodes ?-namespaces prefixUriList? ?-cache <boolean>? ?-list? xpathQuery ?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. IftypeVarargument is given the result type name is stored into that variable (empty,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. 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. π§
Okay so β remember how we said you can inject literals into an XPath expression in a super secure way using Tcl variable references? There's a sibling syntax for injecting element names from Tcl variables too. Anywhere the XPath syntax allows a node test, you can drop in a Tcl variable reference (any form you like), you just swap the leading $ for a %. This is the move when you need to select nodes whose names are 'strange' β as in, invalid according to the appropriate XML production rule β which is exactly the situation you end up in when you're working with JSON data. π¦
-namespacesβ expects a Tcl list of prefix / namespace pairs as its argument. If you don't pass this option, then any namespace prefix inside the xpath expression gets resolved first against the list of prefix / namespace pairs set with theselectNodesNamespacesmethod 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. If you do pass this option, then any namespace prefix inside the xpath expression gets resolved first against the list you gave (and the document-global prefix / namespace list is ignored, sorry bestie). If that list binds the same prefix to different namespaces, the first binding wins. And if that fails too, then the namespace definitions in scope of the context node resolve the prefix, as usual. π-cacheβ if this is used with a true value, then thexpathQuerygets looked up in a document-specific cache. Found it? Then the stored pre-compiled query is what runs. Didn't find it? It gets compiled and stashed in the cache for later calls. β οΈ Important: thexpathQuerygiven as a string is what's used as the key for the cache. Which means equal XPath expressions that differ only in white space are treated as totally different cache entries, not me being dramatic, that's just how it is. 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 you use the same XPath expression later on in a context with other XML prefix namespace mappings or other values of the Tcl variables you used, make sure you first remove the compiled expression from the cache using thedeleteXPathCachemethod, to force a recompilation. Without the-cacheoption you never have to think about any of this. iconic honestly π§-listβ if given, then thexpathQueryargument is expected to be a Tcl list of XPath queries. Every XPath query in that list other than the last one must return a node set result. Using the same context and namespace resolution rules as without-list, the first query out of the list runs. Every node out of that query's result set becomes the context node for the next XPath query out of the list, and so on and so on. It returns the result sets of the last query in the query list, concatenated together. β¨
Examples, as promised:
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]
<h2>πΈ the methods, bestie, get comfy πΈ</h2>
getLineβ returns the line number of that node in the originally parsed XML. Counting starts with 1.getColumnβ returns the column number of that node in the originally parsed XML. Counting starts with 0.getByteIndexβ returns the byte position of that node in the originally parsed XML. Counting starts with 0.asListβ returns the DOM substree starting from the current node as a nested Tcl list.asXMLβ returns the DOM substree starting from the current node as the root node of the result as an (optionally indented) XML string, or sends the output straight to the given channelId. The signature is:
asXML ?-indent none/tabs/1..8? ?-channel channelId? ?-escapeNonASCII?
?-doctypeDeclaration <boolean>? -xmlDeclaration <boolean>? -encString
<string> ?-escapeAllQuot? ?-indentAttrs? ?-nogtescape?
?-noEmptyElementTag? ?-escapeCR? ?-escapeTab?
For a detailed description of the arguments, see the documentation of the domDoc command method asXML.
asCanonicalXMLβ returns the DOM tree as a canonical XML string according to the "Canonical XML Version 1.0 W3C Recommendation 15 March 2001", or sends the output straight to the given channelId. The signature is:
asCanonicalXML ?-channel channelId? ?-comment?
For a detailed description of the arguments, see the documentation of the domDoc command method asCanonicalXML.
asHTMLβ 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, no end tags for empty HTML elements, etc.), as a string, or sends the output straight to the given channelId. The signature is:
asHTML ?-channel channelId? b?-escapeNonASCII? ?-htmlEntities?
?-doctypeDeclaration <boolean>? ?-breakLines? ?-onlyContents?
For a detailed description of the arguments, see the documentation of the domDoc method asHTML.
asTextβ forELEMENT_NODEs, this method outputs the string-value of every text node descendant of node in document order, without any escaping. For every other node type, it outputs the XPath string value of that node.asJSONβ serializes the subtree starting with the node the method was called on into a valid JSON data string. Signature:
asJSON ?-indent none/0..8? ?-channel channelId?
For a detailed description of the method, see the documentation of the domDoc method asJSON.
asTclValueβ if the subtree starting with the node the method was called on includes JSON type information, this method returns the JSON data as a nested Tcl data structure. Signature:
asTclValue ?typevariable?
For a detailed description of the method, see the documentation of the domDoc method asTclValue.
appendFromListlist β parses list, creates an according DOM subtree, and appends that subtree to the current node.appendFromScripttclScript β appends the nodes created in the tclScript by Tcl functions (the ones built usingdom createNodeCmd) to the given node.insertBeforeFromScripttclScript refChild β inserts the nodes created in the tclScript by Tcl functions (again, the ones built usingdom createNodeCmd) before the refChild into the list of children of node. If refChild is the empty string, the new nodes get appended instead. π«ΆappendXMLXMLstring β parses XMLstring, creates an according DOM subtree, and appends that subtree to the current node.simpleTranslateoutputVar 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β returns an XPath which exactly addresses the given node in its document. Heads up: this XPath is only valid as long as no changes to the DOM tree are made later on. With the-legacyoption, other XPath expressions are returned, which don't work in all cases. π¬getBaseURIβ returns the baseURI of the node. This method is deprecated in favor of thebaseURImethod.baseURIβ 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β this method works only for text nodes; for every other node it returns an error. Without the optional argument it returns whether disabling output escaping is on. The return value0means the characters of the text node will be escaped, to generate valid XML, if serialized β and that's 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 value1means output escaping is disabled for this text node. If such a text node is serialized (withasXMLorasHTML), it's literally written, with no 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. I'm so serious, bestie.
precedesrefnode β 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β 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 β meaning there are neither adjacent Text nodes nor empty Text nodes. If the-forXPathoption is given, all CDATA sections in the nodes are converted to text nodes as a first step before the normalization. π§Ήβ¨xsltβ applies an XSLT transformation on the document using the XSLT stylesheet (given asdomDoc). Returns a document object containing the result document of that transformation, and stores it in the optional outputVar. Signature:
xslt ?-parameters parameterList? ?-ignoreUndeclaredParameters?
?-maxApplyDepth int? ?-xsltmessagecmd script? stylesheet ?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. π
-ignoreUndeclaredParametersβ pass this one and any parameter name in the parameterList you hand over to the-parametersoptions that isn't declared as a top-level parameter in the stylesheet just gets... silently ignored π no error, no drama, nothing. Leave it off and it's a whole different vibe: try to set a top-level parameter that the stylesheet never declared and it raises an error. Periodt.-maxApplyDepthβ expects a positive integer as its argument, that's the whole requirement bestie π’. Default tea: the XSLT engine lets XSLT templates nest up to 3000 levels, and if they nest deeper than that it raises an error. This option is literally how you set that limit. ποΈ-xsltmessagecmdβ sets a callback forxslt:messageelements in the stylesheet π£. The actual command is the script (aka whatever you gave as the option's argument) with two things glued onto it: the XML Fragment from instantiating thexsl:messageelement content, as a string (as if the XPathstring()function had been applied to that XML Fragment), plus a flag that tells you whether thexsl:messagehas an attribute"terminate"with the value"yes"π©. And here's the plot twist: if the called script returns anything other thanTCL_OK, the XSLT transformation gets aborted, returning error. If the called script returns-code break, the error message is empty; otherwise the result code is reported. And if the transformation was terminated, theoutputVarβ if given β gets set to the empty string. iykyk@attrNameβ hands you the value of the attributeattrNameβ¨. It's a short cut forgetAttribute, so you can be lazy and iconic about it.jsonType ?(OBJECT|ARRAY|NONE)|(STRING|NUMBER|TRUE|FALSE|NULL|NONE)?β okay so only element and text nodes may have a JSON type, and only this types of nodes support thejsonTypemethod; the other node types return error if you call them with this method π. Returns the jsonType of the node. Give it the optional argument and the JSON type of the node gets set to the given type, then returned. Valid type arguments for element nodes areOBJECT,ARRAYandNONE. Valid type arguments for text nodes areSTRING,NUMBER,TRUE,FALSE,NULLandNONE. slay
Otherwise, if you hit it with an unknown method name, the command with the same name as the given method within the namespace ::dom::domNode gets tried instead π. That's the whole trick β it allows quick method additions on the Tcl level, and honestly? iconic behaviour π«Ά.
π SEE ALSO π
domdomDoc
π KEYWORDS π
XML, DOM, document, node, parsing β
and that's a wrap, bestie π this whole page is domNode(n), coming to you straight from Tcl β go forth and node responsibly, you absolute legend ππ¦
π¦ where this page comes from
- fedora 43: tdom 0.9.6-3.fc43 Β· MPL-2.0 AND MIT
- fedora 44: tdom 0.9.6-3.fc44 Β· MPL-2.0 AND MIT
- nixos 26.05: tdom 0.9.6
- nixpkgs unstable: tdom 0.9.6
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms