当前位置: 首页 > news >正文

根据新浪天气API获取各地天气状况(Java实现)


1.代码块
package com.quickmanager.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * 解析xml文档,包括本地文档和url
 * @author cyxl
 * @version 1.0 2012-05-24
 * @since 1.0
 *
 */
public class XmlParser {
	InputStream inStream;
	Element root;

	public InputStream getInStream() {
		return inStream;
	}

	public void setInStream(InputStream inStream) {
		this.inStream = inStream;
	}

	public Element getRoot() {
		return root;
	}

	public void setRoot(Element root) {
		this.root = root;
	}

	public XmlParser() {
	}

	public XmlParser(InputStream inStream) {
		if (inStream != null) {
			this.inStream = inStream;
			DocumentBuilderFactory domfac = DocumentBuilderFactory
					.newInstance();
			try {
				DocumentBuilder domBuilder = domfac.newDocumentBuilder();
				Document doc = domBuilder.parse(inStream);
				root = doc.getDocumentElement();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public XmlParser(String path) {
		InputStream inStream = null;
		try {
			inStream = new FileInputStream(path);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		if (inStream != null) {
			this.inStream = inStream;
			DocumentBuilderFactory domfac = DocumentBuilderFactory
					.newInstance();
			try {
				DocumentBuilder domBuilder = domfac.newDocumentBuilder();
				Document doc = domBuilder.parse(inStream);
				root = doc.getDocumentElement();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public XmlParser(URL url) {
		InputStream inStream = null;
		try {
			inStream = url.openStream();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		if (inStream != null) {
			this.inStream = inStream;
			DocumentBuilderFactory domfac = DocumentBuilderFactory
					.newInstance();
			try {
				DocumentBuilder domBuilder = domfac.newDocumentBuilder();
				Document doc = domBuilder.parse(inStream);
				root = doc.getDocumentElement();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 
	 * @param nodes
	 * @return 单个节点多个值以分号分隔
	 */
	public Map<String, String> getValue(String[] nodes) {
		if (inStream == null || root==null) {
			return null;
		}
		Map<String, String> map = new HashMap<String, String>();
		// 初始化每个节点的值为null
		for (int i = 0; i < nodes.length; i++) {
			map.put(nodes[i], null);
		}

		// 遍历第一节点
		NodeList topNodes = root.getChildNodes();
		if (topNodes != null) {
			for (int i = 0; i < topNodes.getLength(); i++) {
				Node book = topNodes.item(i);
				if (book.getNodeType() == Node.ELEMENT_NODE) {
					for (int j = 0; j < nodes.length; j++) {
						for (Node node = book.getFirstChild(); node != null; node = node
								.getNextSibling()) {
							if (node.getNodeType() == Node.ELEMENT_NODE) {
								if (node.getNodeName().equals(nodes[j])) {
									//String val=node.getFirstChild().getNodeValue();
									String val = node.getTextContent();
									System.out.println(nodes[j] + ":" + val);
									// 如果原来已经有值则以分号分隔
									String temp = map.get(nodes[j]);
									if (temp != null && !temp.equals("")) {
										temp = temp + ";" + val;
									} else {
										temp = val;
									}
									map.put(nodes[j], temp);
								}
							}
						}
					}
				}
			}
		}
		return map;
	}

}
2.测试代码
<pre name="code" class="html">public static void main(String[] args) {
		String link = "http://php.weather.sina.com.cn/xml.php?city=%D6%D8%C7%EC&password=DJOYnieT8234jlsK&day=0";
		URL url;
		String path = "test.xml";
		try {
			url = new URL(link);
			System.out.println(url);
			// InputStream inStream= url.openStream();
			// InputStream inStream=new FileInputStream(new File("test.xml"));
			XmlParser parser = new XmlParser(url);
			String[] nodes = {"status1","temperature1","temperature2"};
			Map<String, String> map = parser.getValue(nodes);
			System.out.println(map.get(nodes[0]));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

	}
3.结果
 
 
<pre name="code" class="java">http://php.weather.sina.com.cn/xml.php?city=%D6%D8%C7%EC&password=DJOYnieT8234jlsK&day=0
status1:阵雨
temperature1:21
temperature2:18
阵雨


转载学习作品,如若得罪版主。sorry。

有需要的话以下有原链接!


 
 

转载于:https://www.cnblogs.com/laohuihui/p/5308773.html

相关文章:

  • spring的学习
  • 网站通常使用一些javascript包裹 简化电话
  • 我的开始--大道至简的第一章
  • 学习一样新东西行而有效的方法 学习捷径 一项由10个步骤组成的学习方法
  • VS2010中汉字拷贝到Word出现乱码问题解决
  • hdu 5119 Happy Matt Friends (dp)
  • Json.Net系列教程 1.Json.Net介绍及实例
  • PHP 数据结构
  • JavaScript 三种创建对象的方法
  • Java虚拟机(JVM)中的内存设置详解
  • Remove Linked List Elements
  • typeof、offsetof、container_of的解释
  • 转:有关retina和HiDPI那点事
  • C#笔记誊录二
  • Enum:Backward Digit Sums(POJ 3187)
  • SegmentFault for Android 3.0 发布
  • 「译」Node.js Streams 基础
  • 【mysql】环境安装、服务启动、密码设置
  • Angular2开发踩坑系列-生产环境编译
  • pdf文件如何在线转换为jpg图片
  • PHP变量
  • React的组件模式
  • SpringCloud(第 039 篇)链接Mysql数据库,通过JpaRepository编写数据库访问
  • Vue源码解析(二)Vue的双向绑定讲解及实现
  • vue中实现单选
  • weex踩坑之旅第一弹 ~ 搭建具有入口文件的weex脚手架
  • 简单实现一个textarea自适应高度
  • 聊一聊前端的监控
  • 猫头鹰的深夜翻译:JDK9 NotNullOrElse方法
  • 如何借助 NoSQL 提高 JPA 应用性能
  • 如何实现 font-size 的响应式
  • 使用 QuickBI 搭建酷炫可视化分析
  • 微服务入门【系列视频课程】
  • 在Docker Swarm上部署Apache Storm:第1部分
  • 【运维趟坑回忆录 开篇】初入初创, 一脸懵
  • Mac 上flink的安装与启动
  • 好程序员大数据教程Hadoop全分布安装(非HA)
  • 如何在招聘中考核.NET架构师
  • ​iOS实时查看App运行日志
  • ​你们这样子,耽误我的工作进度怎么办?
  • #NOIP 2014# day.1 生活大爆炸版 石头剪刀布
  • #pragma multi_compile #pragma shader_feature
  • #单片机(TB6600驱动42步进电机)
  • #微信小程序:微信小程序常见的配置传值
  • (11)MATLAB PCA+SVM 人脸识别
  • (14)学习笔记:动手深度学习(Pytorch神经网络基础)
  • (C语言)球球大作战
  • (WSI分类)WSI分类文献小综述 2024
  • (八十八)VFL语言初步 - 实现布局
  • (附源码)ssm教材管理系统 毕业设计 011229
  • (考研湖科大教书匠计算机网络)第一章概述-第五节1:计算机网络体系结构之分层思想和举例
  • (蓝桥杯每日一题)平方末尾及补充(常用的字符串函数功能)
  • (源码版)2024美国大学生数学建模E题财产保险的可持续模型详解思路+具体代码季节性时序预测SARIMA天气预测建模
  • **python多态
  • .Net多线程总结