Google Weather API 天气查询程序
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
import java.io.;
import javax.xml.parsers.;
import org.w3c.dom.;
import .;
import java.util.Scanner;
import org.xml.sax.InputSource;
public class Weather{
public static void main(String[] args){
try{Scanner scanner= new Scanner(System.in);获取输入的城市名字
String cityname = scanner.next();
DocumentBuilderFactory cfactory = DocumentBuilderFactory.newInstance(); 获得一个XML的解析器
DocumentBuilder cbuilder = cfactory.newDocumentBuilder(); 解析XML生成DOM
Document cdocument = cbuilder.parse(new File(exmlcities.xml)); cdocument获得对应整个cities.xml的文档树
NodeList cnodelist = cdocument.getElementsByTagName(cityname); 搜索城市标签
Node city = cnodelist.item(0); 定位到城市的节点
Element celement = (Element)city;
String googleapi = celement.getAttribute(data); 获取城市的拼音
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
URL url = new URL(igapihl=zh-cn&weather=+googleapi); 从Google Weahther API
InputStream is = url.openStream(); 获取所选城市的
InputStreamReader isr = new InputStreamReader(is,GBK); XML天气文档
InputSource source = new InputSource(isr);
Document document = builder.parse(source); document是对应于天气文档的文档树
Element element = document.getDocumentElement();根节点
NodeList nodelist = element.getChildNodes();
Node Weather = nodelist.item(0); Weather节点
Element tempelement = (Element) Weather;
NodeList W = tempelement.getChildNodes();
NodeList temp;
Node W1 = W.item(1); 目前天气节点
Node W2 = W.item(2); 今天天气节点
Node W3 = W.item(3); 明天天气节点
Node W4 = W.item(4); 后天天气节点
Node W5 = W.item(5); 大后天天气节点
Element a,b,c,d; 储存天气情况属性的四个节点
打印当前天气
tempelement = (Element) W1;
temp = tempelement.getChildNodes();
a = (Element) temp.item(0);
b = (Element) temp.item(2);
c = (Element)temp.item(3);
d = (Element)temp.item(5);
System.out.println(当前天气:);
System.out.println( +a.getAttribute(data)+ 温度+b.getAttribute(data)+ +c.getAttribute(data)+ +d.getAttribute(data));
打印今天天气
tempelement = (Element) W2;
temp = tempelement.getChildNodes();
a = (Element) temp.item(0);
b = (Element) temp.item(1);
c = (Element)temp.item(2);
d = (Element)temp.item(4);
System.out.println(a.getAttribute(data)+天气:);
System.out.println( +d.getAttribute(data)+ 最低温度+b.getAttribute(data)+ 最高温度:+c.getAttribute(data));
打印明天天气
tempelement = (Element) W3;
temp = tempelement.getChildNodes();
a = (Element) temp.item(0);
b = (Element) temp.item(1);
c = (Element)temp.item(2);
d = (Element)temp.item(4);
System.out.println(a.getAttribute(data)+天气:);
System.out.println( +d.getAttribute(data)+ 最低温度+b.getAttribute(data)+ 最高温度:+c.getAttribute(data));
打印后天天气
tempelement = (Element) W3;