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