我正在使用SAX从谷歌天气API中提取信息,但我遇到了“条件”方面的问题。
具体来说,我使用的是以下代码:
public void startElement (String uri, String name, String qName, Attributes atts) {
if (qName.compareTo("condition") == 0) {
String cCond = atts.getValue(0);
System.out.println("Current Conditions: " + cCond);
currentConditions.add(cCond);
}要从下面这样的内容中提取XML:
http://www.google.com/ig/api?weather=Boston+MA
同时,我试图只获取当天的条件,而不是未来任何一天的条件。
是否有一些检查可以放到xml中,以便仅根据XML文件中的内容提取当天的数据?
谢谢!
发布于 2012-05-09 00:29:40
这应该能起到作用。请记住,如果您使用的是一个框架,那么它可能具有用于XPath的实用函数以使其更简单。
import java.io.IOException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
public class XPathWeather {
public static void main(String[] args)
throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("/tmp/weather.xml");
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("/xml_api_reply/weather/current_conditions/condition/@data");
String result = (String) expr.evaluate(doc, XPathConstants.STRING);
System.out.println(result);
}
}https://stackoverflow.com/questions/10501825
复制相似问题