Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I am trying to delete a existing xml node using a TDOM parser in tclsh script. While trying to delete the node which is not existing, tcl code throws an error.
Is there any way to check the node exists before accessing it in tdom.
This is what I get when trying to delete delNode:
invalid command name ""
while executing
"[$root selectNodes $xpath/delNode] delete"
I'm not sure whether it's practical to check in advance if a node exists before "accessing it in tdom", but that's at least partly because I would never do it that way. The most reasonable way would seem to be to first 1) look for the node, and after that 2) check if any node was found.
$root selectNodes $xpath/delNode
returns a list of zero or more nodes that match the xpath expression you provide1. In this case, it seems no nodes were found. You can test that with e.g. the following:
set nodes [$root selectNodes $xpath/delNode]
if {[llength $nodes]} {
# ...
The part elided with # ...
will only execute if you have at least one node. Another idiom is to iterate over the nodes:
foreach node $nodes {
# ...
This will execute the elided part once for every node, but it won't be executed at all if the list is empty.
If you're confident that only the first node will interest you, you can get it with
set node [lindex $nodes 0]
(If nodes
didn't have any elements, node
will now have the value of an empty string, so you'll still need to check it before using it.)
Bottom line is, the selectNodes
gives you a list of nodes (regardless of whether the expression matched zero, one, or n times. You can test that list with llength
, or look at each node in the list with foreach
, or do any other kind of list processing. If you get one of the elements in the node list inside the variable node
, it will either be the empty string or the name of a command that manages that node.
You check the contents of a variable against the empty string with
if {$node ne {}} {
# ...
In this case, the elided part will be executed if and only if the contents of node
are "not equal" (ne
) to the empty string.
Once you're certain that node
contains a command name, you invoke it with $node argument(s)
.
Documentation: foreach, if, lindex, llength, set
tDOM is documented here: http://tdom.github.io/index.html
1 except for when the expression results in strings.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.