【问题标题】:Parsing XML file in java with conflicting tags在java中解析带有冲突标签的XML文件
【发布时间】:2014-07-24 06:39:45
【问题描述】:

我有一个要在 java 中解析的 XML 文件,并在谷歌地图中使用该 XML 文件的元素。 下面是我必须解析的xml。

      <?xml version = '1.0' encoding = 'UTF-8'?>
      <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
       <channel>
       <title/>
       <link/>
       <description/>
       <item>
        <title> hang </title>
        <description>Total: 291830</description>
         <geo:lat>52.0</geo:lat>
         <geo:long>-6.0</geo:long>
         <dc:subject>category1</dc:subject>
          </item>
          <item>
         <title> system </title>
         <description>Total: 78055</description>
        <geo:lat>36.66992187</geo:lat>
         <geo:long>48.97003173</geo:long>
        <dc:subject>category2</dc:subject>
        </item>
         <item>
          <title>chill </title>
         <description>Total: 43688</description>
         <geo:lat>2.0</geo:lat>
         <geo:long>3.8</geo:long>
         <dc:subject>category3</dc:subject>
          </item>
          </channel>
           </rss>

顶部的标题和描述与根节点项内的标题和描述发生冲突。谁能帮我解析 xml 并获取标题和描述的值??

【问题讨论】:

  • 为什么会有冲突?这看起来像应该是可解析的有效 XML。
  • 它与位于顶部和根节点项内的标题和描述标签混淆了。

标签: java xml


【解决方案1】:

当您想要搜索/查询 XML 文件时,XPath 往往是一个不错的选择,假设您使用的是 DOM...

try {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document dom = db.parse(new File("test.xml"));
    XPath xpath = XPathFactory.newInstance().newXPath();

    // Find the "thing" node...
    XPathExpression expession = xpath.compile("/rss/channel/item/title | /rss/channel/item/description");
    NodeList nl = (NodeList) expession.evaluate(dom, XPathConstants.NODESET);

    for (int index = 0; index < nl.getLength(); index++) {
        Node node = nl.item(index);
        System.out.println(node.getNodeName() + " = " + node.getTextContent());
    }

} catch (Exception exp) {
    exp.printStackTrace();
}

输出

title =  hang 
description = Total: 291830
title =  system 
description = Total: 78055
title = chill 
description = Total: 43688

查看XPath Tutorial了解更多详情...

【讨论】:

  • 我能够获取 title 和 description 的值,但由于冒号,我无法获取 geo:lat 的值...我如何获取该值??
  • 不,我之前没有尝试过...它适用于 lat...谢谢你这么多...:)
猜你喜欢
  • 2020-11-30
  • 2020-07-23
  • 1970-01-01
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多