2013-11-20 40 views
4

我有以下文檔。我正在嘗試獲取test:CategoryABCSite[0]。 嘗試了XPath $ABCCustomerHierarchy(//ata:ABCSite[0])/test:Customer/test:CustomerID/test:Category,但我得到了一些XPath異常。用於XML文檔中索引節點的XPath

誰能告訴我正確的XPath在這裏嗎?

<test:ABCCustomerHierarchy xmlns:test="http://wwwin.test.com/testschema"> 
     <test:ABCSite> 
      <test:Customer> 
       <test:CustomerID> 
        <test:ID>110984181</test:ID> 
        <test:Category>ABC_Customer</test:Category> 
       </test:CustomerID> 
      </test:Customer> 
      <test:CustomerReferences> 
       <test:CustomerID> 
        <test:ID>17808</test:ID> 
        <test:Category>KLM_CUSTOMER</test:Category> 
       </test:CustomerID> 
       <test:CustomerID> 
        <test:ID>17808</test:ID> 
        <test:Category>XYZ_Customer</test:Category> 
       </test:CustomerID> 
       <test:CustomerID> 
        <test:ID>17808</test:ID> 
        <test:Category>PQR_CUSTOMER</test:Category> 
       </test:CustomerID> 
      </test:CustomerReferences> 
     </test:ABCSite> 
     <test:ABCSite> 
      <test:Customer> 
       <test:CustomerID> 
        <test:ID>17808</test:ID> 
        <test:Category>XYZ_Customer</test:Category> 
       </test:CustomerID> 
      </test:Customer> 
      <test:CustomerReferences> 
       <test:CustomerID> 
        <test:ID>17808</test:ID> 
        <test:Category>PQR_CUSTOMER</test:Category> 
       </test:CustomerID> 
      </test:CustomerReferences> 
     </test:ABCSite> 
    </test:ABCCustomerHierarchy> 
+0

請,有編輯box_下方的預覽_right。你的代碼格式非常糟糕。此外,「某些」錯誤消息不起作用,顯示您收到的錯誤消息。 –

回答

0

你應該總是指定命名空間(測試你的例子)

還有一點就是數組從1開始不爲零

如果您想獲得該節點的值,使用文本():

//test:ABCSite[1])/test:Customer/test:CustomerID/test:Category/text() 

,以配合精確值使用:

//test:ABCSite[1])/test:Customer/test:CustomerID/test:Category[text()='ABC_Customer'] 
+0

我問題是如果我比較像// ABCCustomerHierarchy/ABCSite [1]/Customer/CustomerID/Category ='ABC','ABC'將與其父代的索引[1]上的所有ABCSite進行比較。所以我嘗試$ ABCCustomerHierarchy(//測試:ABCSite [1])/測試:客戶/測試:客戶ID /測試:CATEG ORY並得到了異常:javax.xml.transform.TransformerException中:額外非法令牌: – Chris

+0

請參閱本http://stackoverflow.com/q/3674569/2233939 – Chris

+0

然後將[]之前的所有內容放在括號中。我編輯了我的回覆 – evhen14

1

你可以試試:

//ABCCustomerHierarchy/ABCSite[1]/Customer/CustomerID/Category 
+0

沒有。這不會讓我成爲[0]處的節點 – Chris

+1

XPath是1索引的。沒有元素0.如果你想要第一個,@ fastcodejava的解決方案是正確的(但是他省略了命名空間,這可能是一個問題)。嘗試使用與命名空間_your_查詢,但索引1 –

+0

我命名空間嘗試而已,問題是,如果我不喜歡// ABCCustomerHierarchy/ABCSite [1] /客戶/客戶ID /分類比較=「ABC」,「ABC」是被與其母公司指數[1]上的所有ABCSite進行比較。所以我嘗試$ ABCCustomerHierarchy(//測試:ABCSite [1])/測試:客戶/測試:客戶ID /測試:凱特摹ORY並得到了異常:javax.xml.transform.TransformerException中:額外非法令牌: – Chris