2014-03-12 164 views
0

我有xml如下。和默認的命名空間爲http://september.examples.com/setNamespaceContext默認命名空間

addnumber,firstnumber,secondnumber 

XML:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<soapenv:Body> 
<addnumber xmlns="http://september.examples.com/"> 
<firstnumber>10</firstnumber> 
<secondnumber>22</secondnumber> 
</addnumber> 
</soapenv:Body> 
</soapenv:Envelope> 

當我嘗試使用下面的代碼

 factory.setNamespaceAware(true); 
     DocumentBuilder builder = factory.newDocumentBuilder(); 
     Document document = builder.parse(new InputSource(new StringReader(xml))); 
     XPathFactory xpathFactory = XPathFactory.newInstance(); 
     XPath xpath = xpathFactory.newXPath(); 
     xpath.setNamespaceContext(createContext(xml)); 
     String value = xpath.compile("/soapenv:Envelope[1]/soapenv:Body[1]/addnumber[1]/firstnumber[1]").evaluate(document).toString(); 

我歌廳空值從Xpath的獲得價值。由於我在這裏給出的Xpath是addnumber [1]/firstnumber [1]的空名稱空間,我怎樣才能給默認命名空間的xpath?

注:的createContext()將箱子的地圖,其中將包括前綴,URI

回答

1

您可以使用任何前綴來表示默認命名空間,只要它指向同一個URI。只需在函數createContext()中添加指向默認命名空間uri的其他前綴(http://september.examples.com/),然後在XPath表達式中使用它。

相關問題:https://stackoverflow.com/a/6392700/2998271

+0

所以我必須改變我的XPATH也是對的? –

+0

確切地說,在XPath中使用指向默認名稱空間URI的前綴而不是僅包含前綴的元素名稱 – har07

0

XPath 1.0中前綴的名字總是意味着「沒有命名空間」,這是fixed by the spec

的QName在節點測試擴展到使用擴展名錶達式上下文中的名稱空間聲明。除了不使用用xmlns聲明的默認名稱空間外,對開始和結束標籤中的元素類型名稱進行擴展的方式相同:如果QName沒有前綴,則名稱空間URI爲空。 [my bold]

您必須將前綴綁定到上下文中的http://september.examples.com/名稱空間,並在XPath表達式中使用該前綴。