我在打印给定 XML 文件中节点中存在的属性值时遇到问题。我使用该代码并且它编译正确但没有打印任何内容:
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//rss/channel/yweather:location/@city");
Object result = expr.evaluate(doc, XPathConstants.STRING);
System.out.println(result);
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>