我从命令行输出
获得了此XML
示例模板
<config xmlns="http://tail-f.com/ns/config/1.0">
<random xmlns="http://random.com/ns/random/config">
<junk-id>1</junk-id>
<junk-ip-address>1.2.2.3</junk-ip-address>
<junk-state>success</junk-state>
<junk-rcvd>158558</junk-rcvd>
<junk-sent>158520</junk-sent>
<foobar>
<id1>1</id1>
<id2>1</id2>
</foobar>
</random>
</config>
我需要从此junk-state
中提取XML
的值。
我创建了一个.tcl
脚本,使用变量运行并使用单引号 进行测试,如下所示,
以下是我脚本的内容。我只是尝试在节点周围循环,但没有成功。
set XML "<config xmlns='http://tail-f.com/ns/config/1.0'>
<random xmlns='http://random.com/ns/random/config'>
<junk-id>1</junk-id>
<junk-ip-address>1.2.2.3</junk-ip-address>
<junk-state>success</junk-state>
<junk-rcvd>158558</junk-rcvd>
<junk-sent>158520</junk-sent>
<foobar>
<id1>1</id1>
<id2>1</id2>
</foobar>
</random>
</config>"
set doc [dom parse $XML]
set root [$doc documentElement]
set mynode [$root selectNodes "/config/random" ]
foreach node $mynode{
set temp1 [$node text]
echo "temp1 - $temp1"
}
以上脚本不产生输出,
还尝试了如下的直接xpath
表达式并打印文本
set node [$root selectNodes /config/random/junk-state/text()]
puts [$node nodeValue]
puts [$node data
,这会产生错误
invalid command name ""
while executing
"$node nodeValue"
invoked from within
"puts [$node nodeValue]"
(file "temp.tcl" line 41)
我在这里做错了什么。想知道如何使用/修改我的xpath
表达式,因为我发现它更整洁。
$ tclsh
% puts $tcl_version
8.5
% package require tdom
0.8.3
答案 0 :(得分:4)
问题是由xmlns
和config
元素中的XML命名空间(random
属性)引起的。您必须使用-namespace
操作的selectNodes
选项:
package require tdom
set XML {<config xmlns="http://tail-f.com/ns/config/1.0">
<random xmlns="http://random.com/ns/random/config">
<junk-id>1</junk-id>
<junk-ip-address>1.2.2.3</junk-ip-address>
<junk-state>success</junk-state>
<junk-rcvd>158558</junk-rcvd>
<junk-sent>158520</junk-sent>
<foobar>
<id1>1</id1>
<id2>1</id2>
</foobar>
</random>
</config>}
set doc [dom parse $XML]
set root [$doc documentElement]
set node [$root selectNodes -namespace {x http://random.com/ns/random/config} x:random/x:junk-state ]
puts [$node text]
编辑:如果您希望自动从XML检索<random>
元素的命名空间,您可以按照以下方式执行此操作(假设<random>
是唯一的子节点根元素):
set doc [dom parse $XML]
set root [$doc documentElement]
set random [$root childNode]
set ns [$random namespace]
set node [$random selectNodes -namespace [list x $ns] x:junk-state]
puts [$node text]