TCL tDom 空 XML 标签
我使用 tDom 循环一些 XML 并提取每个元素的 text()。
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 设置为空字符串?
I'm using tDom to loop through some XML and pull out each element's text().
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]
}
But when it tries to print out the Vendor, which is empty, it thows the error invalid command name "". How can I ignore this and just set $nVendor to an empty string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
节点的
selectNodes
方法返回与您的模式匹配的节点列表。当您直接使用结果作为命令时,您真正做的是利用 1 个项目 的列表(
name
项目的数量) 是相同的事实作为一件物品。当没有匹配的节点时,您会返回一个空列表,并且当您调用该列表时,它会抛出错误,因为您正在调用名称为
{}
的命令。正如 Hai Vu 所指出的,您可以通过对照
""
检查结果来测试是否有结果。一种“更正确”的方法可能是根据空列表进行检查,或者更完整(如果您不确定输入的 XML)
The
selectNodes
method of a node returns a list of nodes that match your pattern. When you use the results directly as a commandwhat you are really doing is taking advantage of the fact that a list of 1 item (the number of
name
items) is the same as one item. When there are no matching nodes, you get back an empty listand, when you call that, it's throwing an error because you're calling a command with the name
{}
.As noted by Hai Vu, you can test that there was a result by checking the result against
""
. A "more correct" way would probably be to check it against the empty listor, to be even more complete (if you're not sure about the input XML)
您可以检查 $nVendor 是否为空节点:
You can check to see if $nVendor is an empty node: