首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用dom4j解析xml

使用dom4j解析xml
EN

Stack Overflow用户
提问于 2012-12-08 18:21:20
回答 2查看 1.2K关注 0票数 2

我的XML结构是这样的:

代码语言:javascript
运行
复制
<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解析它时

代码语言:javascript
运行
复制
 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;
}
EN

回答 2

Stack Overflow用户

发布于 2012-12-08 18:27:24

在XML和XPath中都有一个未声明的名称空间前缀。

将适当的xmlns:yweather声明添加到XML中,并使用setNamespaceURIs使其对XPath可用。

票数 0
EN

Stack Overflow用户

发布于 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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13776568

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档