xPath使用count获取父节点位置

时间:2015-12-10 18:26:08

标签: xpath

我的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>

1 个答案:

答案 0 :(得分:0)

虽然问题是缺少大量信息,但使用以下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

选择元素节点作为当前节点可能会解决任何问题。

相关问题