TCL TDom: Merging Objects
Using TDom, I would like to view a list of objects in the following format:
<object>
<type>Hardware</type>
<name>System Name</name>
<description>Basic Description of System.</description>
<attributes>
<vendor>Dell</vendor>
<contract>MM/DD/YY</contract>
<supportExpiration>MM/DD/YY</supportExpiration>
<location>Building 123</location>
<serial>xxx-xxx-xxxx</serial>
<mac>some-mac-address</mac>
</attributes>
</object>
<object>
<type>Software</type>
<name>Second Object</name>
...
Then I use TDom to create a list of objects:
set dom [dom parse $xml]
set doc [$dom documentElement]
set nodeList [$doc selectNodes /systems/object]
So far, I've done this to (in theory) select each "object" node from the list. How can I get through them? It's simple:
foreach node $nodeList {
For each object, I need to get the association of each attribute. In this example, I need to remember that "name" is "System Name", "vendor" is "Dell", and so on.
I'm new to TCL, but in other languages I would use an object or an associative list to store them. Is it possible? Can you show me an example syntax for selecting an attribute this way?
source to share
You are really on the right track. You probably want to do this:
foreach node [$doc selectNodes "/systems/object"] {
set name [[$node selectNodes "./name\[1\]"] text]
lappend listOfNames $name
foreach attr {vendor serial} {
set aNodes [$node selectNodes "./attributes/$attr"]
if {[llength $aNodes]} {
set data($name,$attr) [[lindex $aNodes 0] text]
}
}
}
I am using Tcl's (associative) array capabilities to store the extracted attributes. There are other ways that will work as well, such as an iTcl or XOTcl or TclOO object or a dictionary or any number of other possibilities. Keep in mind, I would really be tempted to save the document itself and process it immediately, given how easy it is to actually work with the tDOM; there is no need to fetch everything into some other data structure just for that.
source to share
set doc [$dom documentElement]
set nodeList [$doc selectNodes /systems/object]
foreach node [$nodeList childNodes] {
set nodename [$node nodeName]
if {$nodename eq "attributes"} {
foreach attr_node [$node childNodes] {
set attr_nodename [$attr_node nodeName]
set attr_nodetext [[$attr_node selectNodes text()] nodeValue]
puts "$attr_nodename : $attr_nodetext"
}
} else {
set node_text [[$node selectNodes text()] nodeValue]
puts "$nodename : $node_text"
}
}
check this for quick link https://tdom.github.io/domDoc.html
source to share