2015-12-10 53 views
0

我的xml如下所示。重點是在第三級:<name>,<address>等。我想找到父母<customer>的位置。使用計數來獲取父節點位置的xPath

我使用「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

請提供證明問題的[mcve]。您在評估XPath時忽略瞭如何建立當前節點。 – kjhughes

回答

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 

選擇作爲當前元素節點節點可能會解決任何問題。