关于天气预报应用的实现 dom实现和sax实现


1通过DOM方式读取xml文件



1).注意用dom方式读取文件时,元素节点和元素节点之间不能有空格,要不然读取到的childNodes长度会包括空格

2)创建City类用于封装xml文件中得到的信息

注意最好写上toString()用于检查你代码的错误


3.在dom()方法中写,具体得到的方法,最好在全局实例化,先写factory工厂,再写

package www.csdn.net.xml;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

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

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import www.csdn.domain.City;

public class DOMXML {

	public List<City> domXml() {

		List<City> cities = new ArrayList<City>();

		//
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory
				.newInstance();

		try {
			// 得到文档对象
			DocumentBuilder builder = builderFactory.newDocumentBuilder();

			// 解析具体的xml文件
			// china.xml 放在类路径下
			InputStream is = getClass().getClassLoader().getResourceAsStream(
					"china.xml");

			Document document = builder.parse(is);
			// 返回的是文档的根节点 ( 元素节点 文本节点 属性节点) china
			Element rootElement = document.getDocumentElement();

			// 判断是否有孩子节点
			if (rootElement.hasChildNodes()) {

				// 获取所有子节点

				NodeList childNodes = rootElement.getChildNodes();

				System.out.println("长度:" + childNodes.getLength());

				for (int i = 0; i < childNodes.getLength(); i++) {

					// 获取子节点
					Node node = childNodes.item(i);

					// 判断是元素节点
					// 是元素节点
					if (node.getNodeType() == Element.ELEMENT_NODE) {

						Element element = (Element) node;

						// 得到节点的所有属性
						NamedNodeMap map = element.getAttributes();

						City city = new City();

						// 属性节点
						for (int j = 0; j < map.getLength(); j++) {
							// 获取某个属性节点
							Attr attr = (Attr) map.item(j);
							System.out.println("属性名:" + attr.getName() + "属性值:"
									+ attr.getValue());

							cities.add(new City(element
									.getAttribute("cityName"), element
									.getAttribute("pyName"), element
									.getAttribute("quName"), element
									.getAttribute("state1"), element
									.getAttribute("state2"), element
									.getAttribute("stateDetailed"), element
									.getAttribute("tem1"), element
									.getAttribute("tem2"), element
									.getAttribute("windState")));

							// 属性节点只能一个一个赋值
							
						/*	 if ("cityName".equals(attr.getNodeName())) {
							  city.setCityName(attr.getNodeValue());
							  
							  } else if ("pyName".equals(attr.getNodeName())) {
							 city.setPyName(attr.getNodeValue()); } else if
							  ("quName".equals(attr.getNodeName())) {
							  city.setQuName(attr.getNodeValue()); } else if
							  ("state1".equals(attr.getNodeName())) {
							  city.setState1(attr.getNodeValue()); } else if
							 ("state2".equals(attr.getNodeName())) {
							  city.setState2(attr.getNodeValue()); } else if
							  ("stateDetailed".equals(attr .getNodeName())) {
							 city.setStateDetailed(attr.getNodeValue()); }
							 else if ("tem1".equals(attr.getNodeName())) {
							  city.setTem1(attr.getNodeValue()); } else if
							  ("tem2".equals(attr.getNodeName())) {
							  city.setTem2(attr.getNodeValue()); } else if
							 ("windState".equals(attr.getNodeName())) {
							 city.setWindState(attr.getNodeValue()); }
							  
							  } cities.add(city);
							 */
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cities;
	}
}

4.MainActivity中的代码

package www.csdn.net.weather;

import java.util.List;

import www.csdn.domain.City;
import www.csdn.net.xml.DOMXML;
import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

public class MainActivity extends Activity implements OnCheckedChangeListener {

	private DOMXML domxml;
	private List<City> cities;

	// 申明的空间
	private RadioGroup rg;
	private TextView feng, wen;

	 private int checkedId=1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		

		rg = (RadioGroup) findViewById(R.id.rg);

		rg.setOnCheckedChangeListener(this);

		wen = (TextView) findViewById(R.id.textView1);
		feng = (TextView) findViewById(R.id.textView3);
		
		// 解析XMl文件
		domxml = new DOMXML();
		// 调用响应的方法
		cities = domxml.domXml();

		// 留个思考问题   
		 checkedId = rg.getCheckedRadioButtonId();
		
		//调用封装好的方法  默认值是1  不可以为0   注意代码的顺序  没 rg 怎有rg.getCheckedRadioButtonId()   北京
		initData(checkedId);
		
		

	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		initData(checkedId);

	}

	public void initData(int checkedId) {
		City city = null;
	
		switch (checkedId) {
		case R.id.radio0:
			for (City c : cities) {
				if ("北京".equals(c.getQuName())) {
					city = c;
					System.out.println("radio0===========" +R.id.radio0);
				}
			}
			break;
		case R.id.radio1:
			for (City c : cities) {
				if ("江苏".equals(c.getQuName())) {

					city = c;
					System.out.println("radio1===========" + R.id.radio1);
				}
			}
			break;
		default:
			break;
		}
		if (city != null) {
			System.out.println("city===========" + city);
			wen.setText(city.getTem2() + "°~" + city.getTem1() + "°");
			feng.setText(city.getWindState());
		}
	}
}

二。sax实现

1.xml中的实现必须用标签而不再是属性节点

 
<city>
    
         <cityName>洛阳</cityName>
         <pyName>henan</pyName>
         <quName>河南</quName>
         <state1>4</state1>
         <state2>4</state2>
         <stateDetailed>晴转多云</stateDetailed>
         <tem1>-100</tem1>
         <tem2>100</tem2>
         <windState>华西风5到6级</windState>
  </city>    

2.sax中的代码

package www.csdn.net.know;

import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import www.csdn.domain.City;

public class SaxXML {

	public List<City> saxXML() {
		MyDefaultHandler myHandler = new MyDefaultHandler();
		// 第一步 创建解析器工厂 对象
		SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
		try {
			// 配置的工厂参数   创建实例
			SAXParser saxParser = saxParserFactory.newSAXParser();

			// 第三部 解析xml文件
			saxParser.parse(
					getClass().getClassLoader()
							.getResourceAsStream("china.xml"),
					myHandler);
			//	^_^  肯定是 myHandler相关联    而不是 new MyDefaultHandler(); 
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 思维越来越像了
		return myHandler.getCities();

	}

	// 内部类 事件驱动的处理这
	class MyDefaultHandler extends DefaultHandler {
		private String tagName = null;

		private City currentCity = null;//

		private List<City> cities;

		public List<City> getCities() {

			return cities;
		}

		// 开始解析文档 china city name
		@Override
		public void startDocument() throws SAXException {
			super.startDocument();
			cities = new ArrayList<City>();
		}

		@Override
		public void endDocument() throws SAXException {
			super.endDocument();
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			super.startElement(uri, localName, qName, attributes);

			if (qName.equals("city")) {
				currentCity = new City();
				if (attributes != null) {
					currentCity.setCityName(attributes.getValue("cityName"));
					currentCity.setPyName(attributes.getValue("pyName"));
					currentCity.setQuName(attributes.getValue("quName"));
					currentCity.setState1(attributes.getValue("state1"));
					currentCity.setState2(attributes.getValue("state2"));
					currentCity.setStateDetailed(attributes
							.getValue("stateDetailed"));
					currentCity.setTem1(attributes.getValue("tem1"));
					currentCity.setTem2(attributes.getValue("tem2"));
					currentCity.setWindState(attributes.getValue("windState"));
					
				}
				
				System.out.println("---startElement---" + "uri" + uri
						+ "---localName-" + localName + "----qName--" + qName
						+ "attributes----" + attributes.getValue(qName));
				int length = attributes.getLength();
				
				for (int index = 0; index < length; index++) {
					String attrQName = attributes.getQName(index);
					String attrValue = attributes.getValue(attrQName);
					
					System.out.println(attrQName + "-------" + attrValue);
					
				}
				
			}
			//	^_^注意位置  他要把值 传递给characters
			this.tagName = qName;

		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			super.endElement(uri, localName, qName);
			if (qName.equals("city")) {
				cities.add(currentCity);
				currentCity = null;
			}
			this.tagName = null;
		}

		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			super.characters(ch, start, length);
			if (tagName != null) {
				String value = new String(ch, start, length);
				if (tagName.equals("cityName")) {
					currentCity.setCityName(value);
				} else if (tagName.equals("pyName")) {
					currentCity.setPyName(value);

				} else if (tagName.equals("quName")) {
					currentCity.setQuName(value);

				} else if (tagName.equals("state1")) {
					currentCity.setState1(value);

				} else if (tagName.equals("state2")) {
					currentCity.setState2(value);

				} else if (tagName.equals("stateDetailed")) {
					currentCity.setStateDetailed(value);

				} else if (tagName.equals("tem1")) {
					currentCity.setTem1(value);

				} else if (tagName.equals("tem2")) {
					currentCity.setTem2(value);

				} else if (tagName.equals("windState")) {
					currentCity.setWindState(value);

				}

			}

		}

	}

}

3.mainActivity中的方法

package www.csdn.net.know;


import java.util.List;


import www.csdn.domain.City;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity implements OnItemSelectedListener {


	private Spinner sp_cities;


	private TextView tv_fengli;
	private String[] cities = null;


	private List<City> entities;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);


		/*
		 * List<City> cities =new SaxXML().saxXML();
		 * 
		 * for(City c:cities){ System.out.println(c.toString()); }
		 */
		sp_cities = (Spinner) findViewById(R.id.sp_cities);
		tv_fengli = (TextView) findViewById(R.id.textView2);


		cities = getResources().getStringArray(R.array.cities);
		sp_cities.setOnItemSelectedListener(this);


		sp_cities.setSelection(1);
	}


	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {


		System.out.println(parent + "-------" + view + "----" + position
				+ "--------" + id);
		Toast.makeText(this, cities[position], Toast.LENGTH_LONG).show();


		entities = new SaxXML().saxXML();
		System.out.println(entities);


		for (City c : entities) {
			// System.out.println(c.toString());
			if (c.getQuName().equals(cities[position])) {
				tv_fengli.setText(c.getWindState());
				break;
			}


		}
	}


	@Override
	public void onNothingSelected(AdapterView<?> parent) {


		System.out.println("nothing");


	}


}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值