2012-12-08 67 views
2

我的XML結構是這樣的:解析XML使用dom4j的

<rss> 
    <channel> 
     <yweather:location city="Paris" region="" country="France"/> 
     <yweather:units temperature="C" distance="km" pressure="mb" speed="km/h"/> 
     <yweather:wind chill="-1" direction="40" speed="11.27"/> 
     <yweather:atmosphere humidity="87" visibility="9.99" pressure="1015.92" rising="0"/> 
     <yweather:astronomy sunrise="8:30 am" sunset="4:54 pm"/> 
    </channel> 
</rss> 

,當我試圖使用dom4j的

SAXReader xmlReader = createXmlReader(); 
Document doc = null; 
doc = xmlReader.read(inputStream);//inputStream is input of function 
log.info(doc.valueOf("/rss/channel/yweather:location/@city")); 

private SAXReader createXmlReader() { 
    Map<String,String> uris = new HashMap<String,String>(); 
    uris.put("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0"); 
    uris.put("geo", "http://www.w3.org/2003/01/geo/wgs84_pos#"); 

    DocumentFactory factory = new DocumentFactory(); 
    factory.setXPathNamespaceURIs(uris); 

    SAXReader xmlReader = new SAXReader(); 
    xmlReader.setDocumentFactory(factory); 
    return xmlReader; 
} 

解析它,但我在cmd中什麼都沒有,但是當我打印doc.asXML( ),我的XML結構打印正確!

回答

0

你有一個未聲明的命名空間前綴,無論是在XML和你的XPath。

爲您的XML添加適當的xmlns:yweather聲明,並使用setNamespaceURIs使其可用於您的XPath。

+0

這是我從這個XML的網址: http://weather.yahooapis.com/forecastrss?w=615702&u = c – D3GAN

+0

因此,在原始XML中有一個名稱空間聲明,但是您仍然不會將XPath的前綴'yweather:'設置爲可用。當你解決這個問題會發生什麼? –

+0

XML中有兩個命名空間(正如您可以看到的,如果您點擊此鏈接weather.yahooapis.com/forecastrss?w=615702&u=c) 我將它們兩個添加爲: uris.put(「yweather」,「http ://xml.weather.yahoo.com/ns/rss/1.0「); uris.put(「geo」,「http://www.w3.org/2003/01/geo/wgs84_pos#」); – D3GAN

0

@ D3GAN一切你寫的很好。代碼沒有問題。我只是試過它。問題是你不必在代碼中擁有所有必需的庫。

你應該Jaxen的庫添加到您的類路徑中你可能得到一個NoClassDefFoundError錯誤。原始dom4j分配包含jaxen.jar(在dependancies文件夾中)。

我犯同樣的錯誤。我只是添加了dom4j和代碼沒有工作。我得到的文件是空的。但是當我添加jaxen依賴時,它開始工作正常。

如果你不知道如何安裝JAR文件,你可以去這裏: http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29