2010-04-14 39 views
0

我正在使用tDom來遍歷一些XML並提取每個元素的文本()。TCL tDom空XML標記

set xml { 
<systems> 
<object> 
    <type>Hardware</type> 
    <name>Server Name</name> 
    <attributes> 
    <vendor></vendor> 
    </attributes> 
</object> 
<object> 
    <type>Hardware</type> 
    <name>Server Two Name</name> 
    <attributes> 
    <vendor></vendor> 
    </attributes> 
</object> 
</systems> 
}; 

    set doc [dom parse $xml] 
    set root [$doc documentElement] 

    set nodeList [$root selectNodes /systems/object] 

    foreach node $nodeList { 

    set nType [$node selectNodes type/text()] 
    set nName [$node selectNodes name/text()] 
    set nVendor [$node selectNodes attributes/vendor/text()] 

    # Etc... 
    puts "Type: " 
    puts [$nType data] 

    # Etc .. 

    puts [$nVendor data] 
    } 

但是,當它試圖打印出供應商,這是空的,它會導致錯誤無效命令名稱「」。我怎麼能忽略這一點,只需將$ nVendor設置爲空字符串?

回答

4

節點的selectNodes方法返回匹配您的模式的節點列表。當您直接使用結果作爲命令

set nName [$node selectNodes name/text()] 
puts [$nType data] 

你真的做的是一個事實,即1項(的name項目數)的列表是一樣的一個項目的優勢是什麼。如果沒有匹配的節點,你拿回一個空列表

set nVendor [$node selectNodes attributes/vendor/text()] ;# -> {} 

,當你調用,那是因爲你調用一個名爲{}命令拋出一個錯誤。

set nVendor [$node selectNodes attributes/vendor/text()] ;# -> {} 
puts [$nVendor data] ;# -> winds up calling 
{} data 

正如武海指出,你可以測試有通過檢查對""結果的結果。 A「更正確」的方式很可能是檢查它是否爲空列表

set nVendor [$node selectNodes attributes/vendor/text()] 
if {[llength $nVendor] == 1} { 
    puts [$nVendor data] 
} 

,或者是更完整的(如果你不知道的輸入XML)

set nVendor [$node selectNodes attributes/vendor/text()] 
switch -exact -- [llength $nVendor] { 
    0 { 
     # no nVendor, do nothing 
    } 
    1 { 
     # 1 vendor, print it 
     puts [$nVendor data] 
    } 
    default { 
     # weird, we got more than one vendor node... throw an error 
     error "More than one vendor node" 
    } 
} 
+0

如果你寫XPath的方式稍有不同,你可以保證結果列表中只有0或1的值,並使用'llength'來測試,這是一個簡單的操作。 – 2010-04-15 14:15:54

2

您可以檢查,看看是否$ nVendor是一個空節點:

if {$nVendor != ""} { 
    puts [$nVendor data] 
} 
+0

更好地使用'ne' – 2010-04-15 14:16:21

+0

Donal:謝謝你的指導,我現在知道ne,eq ...應該用於字符串比較,!=,==用於數字。 – 2010-04-15 15:59:56