解析XML使用dom4j的
问题描述:
我的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结构打印正确!
答
@ D3GAN一切你写的很好。代码没有问题。我只是试过它。问题是你不必在代码中拥有所有必需的库。
你应该Jaxen的库添加到您的类路径中你可能得到一个NoClassDefFoundError错误。原始dom4j分配包含jaxen.jar(在dependancies文件夹中)。
我犯同样的错误。我只是添加了dom4j和代码没有工作。我得到的文件是空的。但是当我添加jaxen依赖时,它开始工作正常。
如果你不知道如何安装JAR文件,你可以去这里: http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
这是我从这个XML的网址: http://weather.yahooapis.com/forecastrss?w=615702&u = c – D3GAN
因此,在原始XML中有一个名称空间声明,但是您仍然不会将XPath的前缀'yweather:'设置为可用。当你解决这个问题会发生什么? –
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