【发布时间】: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