domNode(3tcl)

πŸ“¦
version 0.9.6 Β· 4 versions
, in ubuntu resolute, ubuntu stonking

πŸ’… 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_NODE or PROCESSING_INSTRUCTION_NODE. 🏷️
  • nodeName β€” Returns the node name of that node object. So like: it's the element (tag) name for element nodes (type ELEMENT_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 type TEXT_NODE, COMMENT_NODE, PROCESSING_INSTRUCTION_NODE or CDATA_SECTION_NODE. Otherwise it's empty. And if the node is a TEXT_NODE, COMMENT_NODE or PROCESSING_INSTRUCTION_NODE and you passed the optional argument newValue, then boom β€” the node is set to that value. 🫢
  • hasChildNodes β€” Returns 1 if the node has children. Otherwise 0 comes 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 are item <index>, which returns the indexth item in the collection, and length, 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) localname and having the given namespace uri.
  • getElementById id β€” Returns the node having an id attribute with value id, or the empty string if no node has an id attribute with that value. No match, no drama. πŸ™ˆ
  • hasAttribute attributeName β€” Returns 1 if the object node contains an attribute with name attributeName. Otherwise 0 is returned.
  • getAttribute attributeName ?defaultValue? β€” Returns the value of the attribute attributeName. If the attribute is not available, defaultValue is returned.
  • setAttribute attributeName newValue ?attributeName newValue ...? β€” Sets the value for one or more attributes. Every attributeName is set to the corresponding newValue. And if there isn't an attribute for one or more of the attributeNames, 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 attribute attributeName. Bye bye. πŸ‘‹
  • hasAttributeNS uri localName β€” Returns 1 if the object node contains an attribute with the local name localName within the namespace uri. Otherwise 0 is returned.
  • getAttributeNS uri localName ?defaultValue? β€” Returns the value of the attribute with the local name localName within the namespace URI uri. If the node dosn't have that attribute the defaultValue is returned. 😭
  • setAttributeNS uri qualifiedName newValue ?uri qualifiedName newValue ...? β€” Sets the value for one or more full qualified attributes. Every attribute qualifiedName with the namespace URI uri will be set to newValue. 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 name localName within the namespace uri.
  • attributes ?attributeNamePattern? β€” Returns information about the attributes matching the attributeNamePattern. If attributeNamePattern isn'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 the attributeNamePattern. If attributeNamePattern isn't given, all attribute names are returned as a Tcl list.
  • appendChild newChild β€” Appends newChild to the end of the child list of the node. ⭐
  • insertBefore newChild refChild β€” Inserts newChild before the refChild into the list of children of node. And if refChild is the empty string, insert newChild at the end of the child nodes list of that node. Sneaky little shortcut, love that.
  • replaceChild newChild oldChild β€” Replaces oldChild with newChild in the list of children of that node. The oldChild node will be part of the document fragment list after this operation. πŸ¦‹
  • removeChild child β€” Removes child from the list of children of that node. child will 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 -deep option 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 name attrName, and attribute value attrVal in 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 the localName from the tag name of the given node.
  • selectNodes ?-namespaces prefixUriList? ?-cache <boolean>? ?-list? xpathQuery ?typeVar? and xpathQuery ?typeVar? β€” Returns the result of applying the XPath query xpathQuery to 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 the typeVar argument is given, the result type name is stored into that variable (and it'll be one of empty, bool, number, string, nodes, attrnodes or mixed). πŸ‘‘

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 the parameterList you handed to the -parameters options 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 for xslt:message elements 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:message element's content as a string (as if the XPath string() function had been applied to that XML Fragment)
    • a flag that says whether the xsl:message has an attribute "terminate" with the value "yes"

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 for getAttribute, 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 the jsonType method. 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 ✨

  • dom
  • domDoc

πŸ’œ KEYWORDS πŸ’œ

  • XML
  • DOM
  • document
  • node
  • parsing

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