日期:2014-05-20 浏览次数:20776 次
package com.cl.wx.test;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class WeatherTest {
public static void main(String[] args) {
InputStream is = null;
try {
URL u = new URL(
"http://php.weather.sina.com.cn/xml.php?city=上海&password=DJOYnieT8234jlsK&day=1");
HttpURLConnection uConnection = (HttpURLConnection) u
.openConnection();
uConnection.connect();
is = uConnection.getInputStream();
SAXReader reader = new SAXReader();
Document document = reader.read(is);
Element root = document.getRootElement();
Element weather = root.element("Weather");
List<Element> elementList = weather.elements();
Map<String, String> map = new HashMap<String, String>();
for (Element e : elementList)
map.put(e.getName(), e.getText());
System.out.println(map.get("city"));
System.out.println(map.get("gm_s"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}