我的XML结构是这样的:
<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;
}发布于 2012-12-08 18:27:24
在XML和XPath中都有一个未声明的名称空间前缀。
将适当的xmlns:yweather声明添加到XML中,并使用setNamespaceURIs使其对XPath可用。
发布于 2014-04-26 03:22:39
@D3GAN你写的一切都很好。代码没有问题。我刚刚试过了,.The的问题是你的代码中没有所有必要的库。
您应该将jaxen库添加到您的类路径中,您可能会得到一个NoClassdefFoundError。原始的dom4j发行版包含jaxen.jar (在dependancies文件夹中)。
我也犯了同样的错误。我只是添加了dom4j,代码不起作用。我的文档是空的。但是当我添加jaxen依赖时,它就开始正常工作了。
如果您不知道如何安装JAR文件,可以转到此处:http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
https://stackoverflow.com/questions/13776568
复制相似问题