2012-01-10 211 views
6

我試圖確定正確的XPath表達式以返回Body元素上xsi:type屬性的值。我曾嘗試過似乎沒有運氣的一切。根據我讀到的內容看起來很接近,但顯然不適合。任何快速指導,以便我可以終於休息?使用xpath獲取xsi:type的值

//v20:Body/@xsi:type 

我想它返回v20:SmsMessageV1RequestBody

<v20:MessageV1Request> 
    <v20:Header> 
     <v20:Source> 
      <v20:Name>SOURCE_APP</v20:Name> 
      <v20:ReferenceId>1326236916621</v20:ReferenceId> 
      <v20:Principal>2001</v20:Principal> 
     </v20:Source> 
    </v20:Header> 
    <v20:Body xsi:type="v20:SmsMessageV1RequestBody"> 
     <v20:ToAddress>5555551212</v20:ToAddress> 
     <v20:FromAddress>11111</v20:FromAddress> 
     <v20:Message>TEST</v20:Message> 
    </v20:Body> 
</v20:MessageV1Request> 
+4

Xpath表達式對我來說很不錯。你是否在XQUERY,XSLT或其他東西中使用這個XPath?這裏問題最可能的原因是名稱空間前綴引起的混淆。消除名稱空間作爲混淆源的一種方法是將xpath重寫爲:// local_ name()eq'Body']/@ * [local-name()eq'type'] – 2012-01-10 23:28:29

+0

Murray is right ,因爲在XPath中通常有兩種方式來處理名稱空間 - 第一種:使用local-name()和namespace-uri()XPath函數,第二種方法是使用適當的XPath引擎機制 - 例如對於標準JAXP,您必須使用正確配置的NamespaceContext,它將前綴映射到名稱空間。 – 2012-01-11 06:14:31

回答

2

正如指出了意見,你有兩個選擇:

  1. 使用local-name()參考目標節點沒有名稱空間的考慮
  2. 正確地使用XPath引擎註冊所有命名空間

這裏是如何做到在Java中後期:

XPath xpath = XPathFactory.newInstance().newXPath(); 
NamespaceContext ctx = new NamespaceContext() { 
    public String getNamespaceURI(String prefix) { 
     if ("v20".equals(prefix)) { 
      return "testNS1"; 
     } else if ("xsi".equals(prefix)) { 
      return "http://www.w3.org/2001/XMLSchema-instance"; 
     } 
     return null; 
    } 
    public String getPrefix(String uri) { 
     throw new UnsupportedOperationException(); 
    } 
    public Iterator getPrefixes(String uri) { 
     throw new UnsupportedOperationException(); 
    } 
}; 
xpath.setNamespaceContext(ctx); 
XPathExpression expr = xpath.compile("//v20:Body/@xsi:type");  
System.out.println(expr.evaluate(doc, XPathConstants.STRING)); 

請注意,我假設以下命名空間聲明:

<v20:MessageV1Request xmlns:v20="testNS1" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 

你需要更新getNamespaceURI使用實際值。

0

所有優秀的答案/反饋。我的實際問題似乎已經在一個晚上離開了,並在早上重新建立。我會加強反饋。謝謝大家。