2011-12-30 77 views
2

我有下面的XML:Java的XPath表達式

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<application xmlns="http://research.sun.com/wadl/2006/10"> 
<doc xmlns:jersey="http://jersey.dev.java.net/" 
    jersey:generatedBy="Jersey: 1.0.2 02/11/2009 07:45 PM"/> 
<resources base="http://localhost:8080/stock/"> 
    <resource path="categories"> (<<---I want to get here) 
     <method id="getCategoriesResource" name="GET"> 

而且我想要得到的resource/@path的價值,所以我有下面的Java代碼:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
factory.setNamespaceAware(true); // never forget this! 
DocumentBuilder builder = factory.newDocumentBuilder(); 
// get the xml to parse from URI 
Document doc = builder.parse(serviceUri + "application.wadl"); 
XPathFactory xfactory = XPathFactory.newInstance(); 
XPath xpath = xfactory.newXPath(); 
XPathExpression expression = 
     xpath.compile("/application/resources/resource/@path"); 
this.baseUri = (String) expression.evaluate(doc, XPathConstants.STRING); 

有了這個XPath表達式的結果( baseUri)總是空字符串("")。

+0

我不是專家的XPath,但你不解決與'@屬性attribute'只?你有'/ @路徑'。試試'/ application/resources/resource @ path'。 – Thomas 2011-12-30 13:58:55

+2

/application/resources/resource/@ path是解決屬性問題的正確方法 – RanRag 2011-12-30 14:05:22

回答

5

節點不在空字符串名稱空間中,必須指定它:/wadl:application/wadl:resources/wadl:resource/@path。另外,您應該在XPath引擎名稱空間上下文中註冊名稱空間。

這是工作例如:

xpath.setNamespaceContext(new NamespaceContext() 
    { 
     @Override 
     public String getNamespaceURI(final String prefix) 
     { 
      if(prefix.equals("wadl")) 
       return "http://research.sun.com/wadl/2006/10"; 
      else 
       return null; 
     } 

     @Override 
     public String getPrefix(final String namespaceURI) 
     { 
      throw new UnsupportedOperationException(); 
     } 

     @Override 
     public Iterator getPrefixes(final String namespaceURI) 
     { 
      throw new UnsupportedOperationException(); 
     } 
    }); 
    XPathExpression expression = xpath.compile("/wadl:application/wadl:resources/wadl:resource/@path"); 
+0

您的意思是說節點不在* no *命名空間中。它們*在* default *名稱空間中。 – 2012-01-03 20:37:06

+0

@lwburk它是固定的 – kan 2012-01-03 22:56:31