【问题标题】:parsing xml using dom4j使用 dom4j 解析 xml
【发布时间】:2012-12-08 10:21:20
【问题描述】:

我的 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;
}

但是我在 cmd 中什么也没有,但是当我打印 doc.asXML() 时,我的 XML 结构打印正确!

【问题讨论】:

    标签: xml dom4j yahoo-weather-api


    【解决方案1】:

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

    在您的 XML 中添加适当的 xmlns:yweather 声明,并使用 setNamespaceURIs 使其可用于您的 XPath。

    【讨论】:

    【解决方案2】:

    @D3GAN 你写的一切都很好。代码没有问题。我刚试过。问题是你的代码中没有所有必要的库。

    您应该将 jaxen 库添加到您的类路径中,您可能会遇到 NoClassdefFoundError。原始的 dom4j 分发包含 jaxen.jar(在依赖文件夹中)。

    我犯了同样的错误。我刚刚添加了 dom4j 并且代码不起作用。我的文件是空的。但是当我添加 jaxen 依赖时,它开始正常工作。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多