【问题标题】:Getting attributes values from a node in XML file从 XML 文件中的节点获取属性值
【发布时间】:2013-05-14 04:54:44
【问题描述】:

我有一个 XML 文件,我想在其中获取节点属性的值,当节点正常时它可以有效地工作,但是节点的情况是这样命名的:它没有给我任何结果,只是空。 XML 文件:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
<channel>
  <title>Yahoo! Weather - Sunnyvale, CA</title>
  <link>http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/USCA1116_f.html</link>
  <description>Yahoo! Weather for Sunnyvale, CA</description>
  <language>en-us</language>
  <lastBuildDate>Fri, 18 Dec 2009 9:38 am PST</lastBuildDate>
  <ttl>60</ttl>
  <yweather:location city="Sunnyvale" region="CA"   country="United States"/>
  <yweather:units temperature="F" distance="mi" pressure="in" speed="mph"/>
</channel>
</rss>

Java 代码:

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//rss/@version");
Object result = expr.evaluate(doc, XPathConstants.STRING);
System.out.println(result);

以前的 java 代码可以有效地工作,但是将 //rss/@version 替换为 //rss/channel/yweather:location/@city 它返回 null。

【问题讨论】:

  • 您没有在任何地方注册该命名空间。再读一遍你上一题的cmets,一模一样的题。
  • @HovercraftFullOfEels 我也是,没什么可抱怨的 :)

标签: java xml dom xpath xml-parsing


【解决方案1】:

首先,: 之前的部分称为命名空间。它是 XML 中一个相当重要的概念。 要使用命名空间检索值,您必须让上下文知道命名空间。您可以使用

xpath.setNamespaceContext(context);

context 必须是 NamespaceContext 的实现。在这种情况下,命名空间是在 XML 中定义的,因此最好有一个命名空间解析器,它可以直接从文档中获取命名空间。这个类正是这样做的:

public class UniversalNamespaceResolver implements NamespaceContext {
    private Document sourceDocument;

    public UniversalNamespaceResolver(Document document) {
        sourceDocument = document;
    }

    public String getNamespaceURI(String prefix) {
        if (prefix.equals(XMLConstants.DEFAULT_NS_PREFIX)) {
            return sourceDocument.lookupNamespaceURI(null);
        } else {
            return sourceDocument.lookupNamespaceURI(prefix);
        }
    }

    public String getPrefix(String namespaceURI) {
        return sourceDocument.lookupPrefix(namespaceURI);
    }

    public Iterator getPrefixes(String namespaceURI) {
        return null;
    }
}

http://www.ibm.com/developerworks/library/x-nmspccontext/了解更多信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多