`

sax解析xml案例一

 
阅读更多

本文出自:http://www.cnblogs.com/linjiqin/archive/2011/03/11/1981076.html

student.xml文件

<?xml version="1.0" encoding="UTF-8"?> <StudentInfo> <student> <name>赵海波</name> <sex></sex> <lesson> <lessonName>Spring整合开发</lessonName> <lessonScore>85</lessonScore> </lesson> <lesson> <lessonName>轻量级J2EE应用开发</lessonName> <lessonScore>95</lessonScore> </lesson> <lesson> <lessonName>Ajax应用开发</lessonName> <lessonScore>80</lessonScore> </lesson> </student> <student> <name>程卫娜</name> <sex></sex> <lesson> <lessonName>Spring整合开发</lessonName> <lessonScore>80</lessonScore> </lesson> <lesson> <lessonName>轻量级J2EE应用开发</lessonName> <lessonScore>85</lessonScore> </lesson> <lesson> <lessonName>Ajax应用开发</lessonName> <lessonScore>90</lessonScore> </lesson> </student> </StudentInfo>

fuzhou_weather.xml文件

<?xml version="1.0" encoding="UTF-8"?> <!-- 福州的天气情况 --> <xml_api_reply version="1"> <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0"> <forecast_information> <city data="Fuzhou, Fujian" /> <postal_code data="fuzhou" /> <latitude_e6 data="" /> <longitude_e6 data="" /> <forecast_date data="2011-01-08" /> <current_date_time data="2011-01-08 23:00:00 +0000" /> <unit_system data="SI" /> </forecast_information> <current_conditions> <condition data="多云" /> <temp_f data="53" /> <temp_c data="12" /> <humidity data="湿度: 43%" /> <icon data="/ig/images/weather/mostly_cloudy.gif" /> <wind_condition data="风向: 东北、风速:1 米/秒" /> </current_conditions> <forecast_conditions> <day_of_week data="周六" /> <low data="7" /> <high data="14" /> <icon data="/ig/images/weather/chance_of_rain.gif" /> <condition data="可能有雨" /> </forecast_conditions> <forecast_conditions> <day_of_week data="周日" /> <low data="6" /> <high data="12" /> <icon data="/ig/images/weather/chance_of_rain.gif" /> <condition data="可能有雨" /> </forecast_conditions> <forecast_conditions> <day_of_week data="周一" /> <low data="5" /> <high data="10" /> <icon data="/ig/images/weather/mostly_sunny.gif" /> <condition data="晴间多云" /> </forecast_conditions> <forecast_conditions> <day_of_week data="周二" /> <low data="4" /> <high data="8" /> <icon data="/ig/images/weather/chance_of_rain.gif" /> <condition data="可能有雨" /> </forecast_conditions> </weather> </xml_api_reply>

学生Student类

package com.ljq.entity; import java.util.Set; /** * 学生信息表 * * @author jiqinlin * */ public class Student { /** 姓名 * */ private String name; /** 性别 * */ private String sex; /** 所学课程 * */ private Set<Lesson> lessons; public Student() { } public Student(String name, String sex, Set<Lesson> lessons) { this.name = name; this.sex = sex; this.lessons = lessons; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Set<Lesson> getLessons() { return lessons; } public void setLessons(Set<Lesson> lessons) { this.lessons = lessons; } }

课程Lesson类

package com.ljq.entity; /** * 课程 * * @author jiqinlin * */ public class Lesson { /** 课程名称 * */ private String lessonName; /** 课程成绩 * */ private int lessonScore; public Lesson() { } public Lesson(String lessonName, int lessonScore) { this.lessonName = lessonName; this.lessonScore = lessonScore; } public String getLessonName() { return lessonName; } public void setLessonName(String lessonName) { this.lessonName = lessonName; } public int getLessonScore() { return lessonScore; } public void setLessonScore(int lessonScore) { this.lessonScore = lessonScore; } }

当前天气信息的类Weather

package com.ljq.entity; import java.util.List; /** * 当前天气信息的类 * * @author jiqinlin * */ public class Weather { /** 城市 * */ private String city; /** 当天日期,格式为yyyy-mm-dd * */ private String forecase_date; /** 当前时间 * */ private String current_date_time; /** 现象描述 * */ private String current_condition; /** 当前干燥程度 * */ private String current_humidity; /** 当前图片地址 * */ private String current_image_url; /** 风向 * */ private String current_wind; /** 此处只能用有序的List集合,因为第一位索引表示当天的天气情况 **/ private List<Forecast> forecasts; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getForecase_date() { return forecase_date; } public void setForecase_date(String forecase_date) { this.forecase_date = forecase_date; } public String getCurrent_date_time() { return current_date_time; } public void setCurrent_date_time(String current_date_time) { this.current_date_time = current_date_time; } public String getCurrent_condition() { return current_condition; } public void setCurrent_condition(String current_condition) { this.current_condition = current_condition; } public String getCurrent_humidity() { return current_humidity; } public void setCurrent_humidity(String current_humidity) { this.current_humidity = current_humidity; } public String getCurrent_image_url() { return current_image_url; } public void setCurrent_image_url(String current_image_url) { this.current_image_url = current_image_url; } public String getCurrent_wind() { return current_wind; } public void setCurrent_wind(String current_wind) { this.current_wind = current_wind; } public List<Forecast> getForecasts() { return forecasts; } public void setForecasts(List<Forecast> forecasts) { this.forecasts = forecasts; } }

未来天气信息的类Forecast

package com.ljq.entity; /** * 未来天气信息的类 * * @author jiqinlin * */ public class Forecast { /** 星期几 * */ private String day_of_week; /** 最低温度 * */ private String low; /** 最高温度 * */ private String high; /** 图片地址 * */ private String image_url; /** 现象描述 * */ private String condition; public String getDay_of_week() { return day_of_week; } public void setDay_of_week(String day_of_week) { this.day_of_week = day_of_week; } public String getLow() { return low; } public void setLow(String low) { this.low = low; } public String getHigh() { return high; } public void setHigh(String high) { this.high = high; } public String getImage_url() { return image_url; } public void setImage_url(String image_url) { this.image_url = image_url; } public String getCondition() { return condition; } public void setCondition(String condition) { this.condition = condition; } }

StudentSax解析

package com.ljq.sax; import java.util.HashSet; import java.util.Set; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import com.ljq.entity.Lesson; import com.ljq.entity.Student; public class StudentSax extends DefaultHandler { private Lesson lesson; private Set<Lesson> lessons; private Student student; private Set<Student> students; private String preTag; @Override public void startDocument() throws SAXException { lessons = new HashSet<Lesson>(); students = new HashSet<Student>(); } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (student != null) { String data = new String(ch, start, length); if ("name".equals(preTag)) { student.setName(data); } if ("sex".equals(preTag)) { student.setSex(data); } if ("lessonName".equals(preTag)) { lesson.setLessonName(data); } if ("lessonScore".equals(preTag)) { lesson.setLessonScore(Integer.parseInt(data)); } } } @Override public void startElement(String uri, String localName, String name, Attributes attr) throws SAXException { if ("student".equals(name)) { student = new Student(); } if ("lesson".equals(name)) { lesson = new Lesson(); } preTag = name; } @Override public void endElement(String uri, String localName, String name) throws SAXException { if (student != null && "student".equals(name)) { student.setLessons(lessons); students.add(student); student = null; lessons = new HashSet<Lesson>(); } if (lesson != null && "lesson".equals(name)) { lessons.add(lesson); lesson = null; } preTag = null; } public Set<Student> getStudents() { return students; } public Set<Lesson> getLessons() { return lessons; } }

WeatherSax解析

package com.ljq.sax; import java.util.ArrayList; import java.util.List; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import com.ljq.entity.Forecast; import com.ljq.entity.Weather; public class WeatherSax extends DefaultHandler { private Weather weather; private Forecast forecast; private List<Forecast> forecasts; private String preTag; @Override public void startDocument() throws SAXException { weather = new Weather(); forecasts = new ArrayList<Forecast>(); } @Override public void characters(char[] ch, int start, int length) throws SAXException { } @Override public void startElement(String uri, String localName, String name, Attributes attr) throws SAXException { if ("city".equals(name)) { weather.setCity(attr.getValue("data")); // 等价于weather.setCity(attr.getValue("data")); } if ("forecast_date".equals(name)) { weather.setForecase_date(attr.getValue("data")); } if ("current_date_time".equals(name)) { weather.setCurrent_date_time(attr.getValue("data")); } if("current_conditions".equals(name)){ preTag = name; } if ("condition".equals(name) && "current_conditions".equals(preTag)) { weather.setCurrent_condition(attr.getValue("data")); } if ("humidity".equals(name)) { weather.setCurrent_humidity(attr.getValue("data")); } if ("icon".equals(name) && "current_conditions".equals(preTag)) { weather.setCurrent_image_url(attr.getValue("data")); } if ("wind_condition".equals(name)) { weather.setCurrent_wind(attr.getValue("data")); } if ("forecast_conditions".equals(name)) { preTag = name; // 记录标识,用来区分相同节点的不同父节点 forecast = new Forecast(); } if ("day_of_week".equals(name)) { forecast.setDay_of_week(attr.getValue("data")); } if ("low".equals(name)) { forecast.setLow(attr.getValue("data")); } if ("high".equals(name)) { forecast.setHigh(attr.getValue("data")); } if ("icon".equals(name) && "forecast_conditions".equals(preTag)) { forecast.setImage_url(attr.getValue("data")); } if ("condition".equals(name) && "forecast_conditions".equals(preTag)) { forecast.setCondition(attr.getValue("data")); } } @Override public void endElement(String uri, String localName, String name) throws SAXException { if ("forecast_conditions".equals(name)) { forecasts.add(forecast); forecast = null; } if ("weather".equals(name)) { weather.setForecasts(forecasts); } } public Weather getWeather() { return weather; } }

StudentSaxTest测试类

package com.ljq.test; import java.io.InputStream; import java.util.Set; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import com.ljq.entity.Lesson; import com.ljq.entity.Student; import com.ljq.sax.StudentSax; public class StudentSaxTest { public static void main(String[] args) throws Exception { Set<Student> students = new StudentSaxTest().parseXMLFile(); for(Student stu : students){ System.out.println("name=" + stu.getName()); System.out.println("sex=" + stu.getSex()); Set<Lesson> lessons = stu.getLessons(); for(Lesson lesson : lessons){ System.out.println("LessonName = " + lesson.getLessonName()); System.out.println("LessonScore = " + lesson.getLessonScore()); System.out.println("---------------"); } System.out.println("=========="); } } // 解析文档 private Set<Student> parseXMLFile() throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); InputStream is = StudentSaxTest.class.getClassLoader() .getResourceAsStream("student.xml"); StudentSax handle = new StudentSax(); saxParser.parse(is, handle); is.close(); return handle.getStudents(); } }

WeatherSaxTest测试类

package com.ljq.test; import java.io.InputStream; import java.util.List; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import com.ljq.entity.Forecast; import com.ljq.entity.Weather; import com.ljq.sax.WeatherSax; public class WeatherSaxTest { public static void main(String[] args) throws Exception{ Weather weather = new WeatherSaxTest().readXml(); System.out.println("city=" + weather.getCity()); System.out.println("forecase_date=" + weather.getForecase_date()); System.out.println("current_date_time=" + weather.getCurrent_date_time()); System.out.println("condition=" + weather.getCurrent_condition()); System.out.println("humidity=" + weather.getCurrent_humidity()); System.out.println("icon=" + weather.getCurrent_image_url()); System.out.println("wind_condition=" + weather.getCurrent_wind()); System.out.println("==========="); List<Forecast> forecasts = weather.getForecasts(); for(Forecast forecast : forecasts){ System.out.println("day_of_week=" + forecast.getDay_of_week()); System.out.println("low=" + forecast.getLow()); System.out.println("high=" + forecast.getHigh()); System.out.println("icon=" + forecast.getImage_url()); System.out.println("condition=" + forecast.getCondition()); System.out.println("---------------"); } } private Weather readXml() throws Exception{ SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); InputStream is = WeatherSaxTest.class.getClassLoader().getResourceAsStream("fuzhou_weather.xml"); WeatherSax handle = new WeatherSax(); parser.parse(is, handle); is.close(); return handle.getWeather(); } }

分享到:
评论

相关推荐

    Android SAX、DOM、Pull解析xml文件案例讲解

    读取和解析xml文件

    xml解析案例

    主要是进一步加深对xml基础的理解了使用,毕竟基础是恶化你重要的嘛!...主要内容有xml语法、DOM解析、SAX解析、Xpath,schema约束。 xml案例代码: 博客地址:http://blog.csdn.net/sdksdk0/article/details/51555090

    java中xml解析

    该案例包含java中dom解析xml、sax解析xml以及dom4j解析xml(或者理解为jdom解析),希望能帮到一些人

    xml文档草错

    本案例介绍了dom4j和sax解析xml文档,有利于初学者的学习,并附dom4j操作文档

    疯狂XML讲义 源码

    第三部分介绍了DOM、SAX、JAXP、dom4j、JDOM、XQuery和XQJ等,其中的DOM、SAX、JAXP、dom4i和JDOM都以结构化的方式来创建、解析XML文档,从而可以将XML文档作为数据传输工具,而XQuery则是一种新规范,通过X Query...

    疯狂xml讲义

    第三部分介绍了DOM、SAX、JAXP、dom4j、JDOM、XQuery和XQJ等,其中的DOM、SAX、JAXP、dom4j和JDOM都以结构化的方式来创建、解析XML文档,从而可以将XML文档作为数据传输工具,而XQuery则是一种新规范,通过XQuery...

    疯狂XML讲义.part3.rar

    第三部分介绍了DOM、SAX、JAXP、dom4j、JDOM、XQuery和XQJ等,其中的DOM、SAX、JAXP、dom4j和JDOM都以结构化的方式来创建、解析XML文档,从而可以将XML文档作为数据传输工具,而XQuery则是一种新规范,通过XQuery...

    疯狂XML讲义

    第三部分介绍了DOM、SAX、JAXP、dom4j、, JDOM、XQuery和XQJ等,其中的DOM、SAX、JAXP、dom4j和JDOM都以结构化的, 方式来创建、解析XML文档,从而可以将XML文档作为数据传输工具,而, XQuery则是一种新规范,通过...

    疯狂XML讲义(Web Service).pdf

    第三部分介绍了DOM、SAX、JAXP、dom4j、JDOM、XQuery和XQJ等,其中的DOM、SAX、JAXP、dom4j和JDOM都以结构化的方式来创建、解析XML文档,从而可以将XML文档作为数据传输工具,而XQuery则是一种新规范,通过XQuery...

    疯狂XML讲义.part1

    第三部分介绍了DOM、SAX、JAXP、dom4j、JDOM、XQuery和XQJ等,其中的DOM、SAX、JAXP、dom4j和JDOM都以结构化的方式来创建、解析XML文档,从而可以将XML文档作为数据传输工具,而XQuery则是一种新规范,通过XQuery...

    疯狂XML讲义.part2.rar

    第三部分介绍了DOM、SAX、JAXP、dom4j、JDOM、XQuery和XQJ等,其中的DOM、SAX、JAXP、dom4j和JDOM都以结构化的方式来创建、解析XML文档,从而可以将XML文档作为数据传输工具,而XQuery则是一种新规范,通过XQuery...

    JDOM(java)使用详解及实例

    1、org.JDOM这个包里的类是你J解析xml文件后所要用到的所有数据类型。 Attribute CDATA Coment DocType Document Element EntityRef Namespace ProscessingInstruction Text 2、org.JDOM.transform在涉及...

    JAVA 范例大全 光盘 资源

    实例108 SAX解析XML文件 297 实例109 W3C解析XML文件 301 第13章 Java网络编程 306 实例110 获取IP地址和域名 306 实例111 获取网络资源(URL) 308 实例112 FTP文件传输模拟 311 实例113 自制浏览器 316 ...

    Android典型技术模块开发详解

    第1章 Android初识 1.1 Android简介 1.1.1 认识Android 1.1.2 Android系统框架 1.1.3 应用程序框架 1.2 Eclipse开发环境 1.2.1 安装ADT插件 1.2.2 安装SDK 1.2.3 配置源代码 1.2.4 创建AVD 1.3 Android模拟器 1.3.1 ...

Global site tag (gtag.js) - Google Analytics