我正在使用SAX从Google天气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文件中的内容提取当天的数据?
谢谢!
答案 0 :(得分:1)
这应该可以解决问题。请记住,如果您正在使用框架,那么它可能具有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);
}
}