Xml TCL-TDom:通过对象循环

Xml TCL-TDom:通过对象循环,xml,parsing,tcl,tdom,Xml,Parsing,Tcl,Tdom,使用TDom,我想循环浏览以下格式的对象列表: <object> <type>Hardware</type> <name>System Name</name> <description>Basic Description of System.</description> <attributes> <vendor>D

使用TDom,我想循环浏览以下格式的对象列表:

    <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>
    ...
到目前为止,我已经(理论上)从列表中选择了每个“对象”节点。我怎样才能循环通过它们?只是:

foreach node $nodeList { 
对于每个对象,我需要检索每个属性的关联。从这个例子中,我需要记住,“名称”是“系统名称”,“供应商”是“戴尔”,等等


我是TCL新手,但在其他语言中,我会使用对象或关联列表来存储这些内容。这可能吗?您能给我举一个这样选择属性的语法示例吗?

您的思路确实正确。您可能想这样做:

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]
        }
    }
}
我正在使用Tcl的(关联)数组功能来保存提取的属性。还有其他方法也可以使用,例如,iTcl或XOTcl或TclOO对象,或字典,或任何其他可能性。请注意,考虑到实际使用tDOM是多么容易,我实际上很想保留文档本身并直接进行处理;不需要将所有内容都提取到其他数据结构中,只是为了好玩

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"
    }
}

查看此快速参考

谢谢您的帮助,这正是我需要的。您是对的,我可能最好直接从tDOM使用每个属性。我的下一个冒险是将每个解析的对象构建到数据库对象中。乐趣:-)最重要的是准确地计划你想要实现什么,哪些作品应该去哪里,等等。我发现信封的背面是一个做这些计划的好地方。:-)
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"
    }
}