我正在创建一个天气应用程序,它从具有相同节点名称的5天预测XML中获取最小/最大温度。我想使用当前日期查看XML并找到当天的正确最小值/最大值。
这是天气XML:Link
这是我的代码,我已经将它修剪得足够我不理解多节点的部分,但我仍然希望它可以重复使用(目前它只是得到第一个最小值/最大值,如下所示a 0):
public class MyAsyncTask extends AsyncTask < Void, Void, String > {
//========================== pre execute to get date for xml =======
protected void onPreExecute() {
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
} catch (Exception e) {}
}@
Override
protected String doInBackground(Void...params) {
//=========================== Load data using xml ================
try {
URL xmlUrl2 = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=london&mode=xml&units=metric&cnt=5");
InputStream inm = xmlUrl2.openStream();
Document docm = parsem(inm);
docm.getDocumentElement().normalize();
Node nNodem = docm.getElementsByTagName("temperature").item(0);
Element eElementm = (Element) nNodem;
double dmax = Math.round(Double.parseDouble(eElementm.getAttribute("max")));
int dxmax = (int) dmax;
xmaxtemp = Integer.toString(dxmax);
double dmin = Math.round(Double.parseDouble(eElementm.getAttribute("min")));
int dxmin = (int) dmin;
xmintemp = Integer.toString(dxmin);
} catch (UnknownHostException s) {
internet = false;
} catch (IOException i) {
System.out.println("IO Exception error!");
} catch (Exception ex) {
ex.printStackTrace();
}
return xtemp;
}
//========================= show data===============
@
Override
protected void onPostExecute(String result) {
TextView minmax = (TextView) findViewById(R.id.minmax);
minmax.setText("↑" + xmaxtemp + " " + xmintemp + "↓");
}
//======================== parse document =======
public static Document parse(InputStream is) {
Document ret = null;
DocumentBuilderFactory domFactory;
DocumentBuilder builder;
try {
domFactory = DocumentBuilderFactory.newInstance();
domFactory.setValidating(false);
domFactory.setNamespaceAware(false);
builder = domFactory.newDocumentBuilder();
ret = builder.parse(is);
} catch (Exception ex) {
System.err.println("unable to load XML: " + ex);
}
return ret;
}
}
答案 0 :(得分:0)
为了更好地使用,你应该使用xpath对ur xml数据进行完美的操作:
这是一个如何获取所有温度节点
的示例String expression = "//temperature";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
之后你可以操纵清单。
这是一个很好的tuto开始使用xpath与java: java-xml-xpath-tutorial/