我的xml如下所示。焦点在第三个层次:<name>
、<address>
等。我想找到父<customer>
的位置。
我使用"count(../preceding-sibling::*) + 1
",但当节点为空时,它不会返回计数。我该如何解决这个问题?谢谢
<record>
<customer>
<name>Sue A</name> -- return 1
<address>123 Main St</address> -- return 1
<phone></phone> -- missing
<status>A</status> -- return 1
</customer>
<customer>
<name>John B</name> -- return 2
<address></address> -- missing
<phone>123-456-7890</phone> -- return 2
<status></status> -- missing
</customer>
…
</record>
虽然这个问题缺乏很多信息,但使用以下xquery看起来您的逻辑是正确的,但您可能使用文本节点作为当前节点,而不是元素节点。
此查询返回相同的错误结果,因为缺少一些文本节点:
let $x :=
for $grandchild in //customer/*/text()
return count($grandchild/../../preceding-sibling::*) + 1
return $x
这个查询返回正确的结果,因为每个元素都存在:
let $x :=
for $child in //customer/*
return count($child/../preceding-sibling::*) + 1
return $x
选择元素节点作为当前节点可能会解决任何问题。