您的位置:首页 > 其它

PULL方式解析xml

2014-04-01 17:59 190 查看
本文讲述: 用pull 方式解析xml ,需要导入 kxml2-2.2.2.jar 包 。 这种解析方法很简单,只用到 3个类: XmlPullParserFactory , XmlPullParser , XmlPullParserException 。用法见程序。

persons.xml

<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="23">
<name>黄老师</name>
<age>26</age>
</person>
<person id="25">
<name>杨老师</name>
<age>28</age>
</person>
</persons>

客户端左 和 服务器端右 目录:

  

        


  ,

程序运行结果:

Person [id=23, name=黄老师, age=26]
Person [id=25, name=杨老师, age=28]


客户端Person.java

package com.pull.data;

public class Person {

private int id ;
private String name ;
private int age;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}

}


客户端HttpUtils.java

package com.pull.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtils {

public HttpUtils() {
// TODO Auto-generated constructor stub
}

public static InputStream getXML(String path) {

InputStream inputStream = null;

try {
URL url = new URL(path);

if (url != null) {
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setDoInput(true); // 从服务器获取数据
httpURLConnection.setRequestMethod("GET");

int responseCode = httpURLConnection.getResponseCode();

if (responseCode == 200) {
inputStream = httpURLConnection.getInputStream();
}
}

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return inputStream;

}

}


客户端 PullXMLTools.java

package com.pull.parser;

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

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.pull.data.Person;

/*
* 主要完成 使用 PULL解析 XML
* */
public class PullXMLTools {

public PullXMLTools() {
// TODO Auto-generated constructor stub
}

/**
* @param inputStream
*            从服务器获得xml文件,以流的形式返回。
* @param encode
*            编码方式
* @return
* @throws Exception
*/
public static List<Person> parseXML(InputStream inputStream, String encode)
throws Exception {

List<Person> list = null;
Person person = null; // person 用来装载每一个person对象

// 创建一个xml解析工厂
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
// 获取一个xml解析器引用
XmlPullParser parser = factory.newPullParser();
parser.setInput(inputStream, encode);
// 获取事件类型
int eventType = parser.getEventType();

while (eventType != XmlPullParser.END_DOCUMENT) {

switch (eventType) {
case XmlPullParser.START_DOCUMENT:
list = new ArrayList<Person>();
break;

case XmlPullParser.START_TAG:

if ("person".equals(parser.getName())) {
person = new Person();
int id = Integer.parseInt(parser.getAttributeValue(0));
person.setId(id);

} else if ("name".equals(parser.getName())) {
String name = parser.nextText(); // 获取该节点的内容
person.setName(name);

} else if ("age".equals(parser.getName())) {
int age = Integer.parseInt(parser.nextText());
person.setAge(age);
}
break;
case XmlPullParser.END_TAG:

if ("person".equals(parser.getName())) {
list.add(person);
person = null;
}

break;
}

eventType = parser.next(); // 循环到下一个节点
}

return list;
}

}


客户端 Test.java

package com.pull.test;

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

import com.pull.data.Person;
import com.pull.http.HttpUtils;
import com.pull.parser.PullXMLTools;

public class Test {

public Test() {
// TODO Auto-generated constructor stub
}

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub

String path = "http://192.168.0.102:8080/myhttp/persons.xml";
InputStream inputStream = HttpUtils.getXML(path);
List<Person> list = PullXMLTools.parseXML(inputStream, "utf-8");

for (Person person : list) {

System.out.println(person.toString());
}

}

}


服务器端 LoginAction.java

package com.login.manager;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginAction extends HttpServlet {

/**
* Constructor of the object.
*/
public LoginAction() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

this.doPost(request, response);
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//客户端 HttpUtils并没有写request方法是post ,但服务器端可自动识别
String method = request.getMethod();
System.out.println("request method :"+method);

PrintWriter out = response.getWriter();
String username = request.getParameter("username");
System.out.println("-username->>"+username);

String password = request.getParameter("password");
System.out.println("-password->>"+password);

if (username.equals("admin") && password.equals("123")) {
// 表示服务器段返回的结果
out.print("login is success !");

} else {
out.print("login is fail !");
}

out.flush();
out.close();
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}

*************************************************************************************************

用PULL方法解析另外两个典型的xml : student.xml 和  weather.xml

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>

student.xml测试结果:

Name :宋慧乔
Sex :女
LessonName :Spring整合开发
LessonScore :80
LessonName :Ajax应用开发
LessonScore :90
LessonName :轻量级J2EE应用开发
LessonScore :85
-----------------------------
Name :刘德华
Sex :男
LessonName :Spring整合开发
LessonScore :85
LessonName :Ajax应用开发
LessonScore :80
LessonName :轻量级J2EE应用开发
LessonScore :95
-----------------------------

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="ShenZhen, GuangDong" />
<postal_code data="shenzhen" />
<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>

weather.xml测试结果:

深圳今天天气预报:

城市 :ShenZhen, GuangDong
当前天气 :多云
当前湿度:湿度: 43%
当前风力 :风向: 东北、风速:1 米/秒
当前图标 :/ig/images/weather/mostly_cloudy.gif
当前日期 :2011-01-08
当前时间 :2011-01-08 23:00:00 +0000
-------------------------------------------

未来几天的天气预报:

日期:周六
天气情况:可能有雨
最低温度:7
最高温度:14
气象图标:/ig/images/weather/chance_of_rain.gif
********************************************
日期:周日
天气情况:可能有雨
最低温度:6
最高温度:12
气象图标:/ig/images/weather/chance_of_rain.gif
********************************************
日期:周一
天气情况:晴间多云
最低温度:5
最高温度:10
气象图标:/ig/images/weather/mostly_sunny.gif
********************************************
日期:周二
天气情况:可能有雨
最低温度:4
最高温度:8
气象图标:/ig/images/weather/chance_of_rain.gif
********************************************


Student.java

package com.pull.data;

import java.util.Set;

public class Student {

private String name ;
private String sex;
private Set<Lesson> lessons;

public Student() {
// TODO Auto-generated constructor stub
}

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.java

package com.pull.data;

public class Lesson {

private String lessonName ; //课程名称
private String lessonScore ; //课程分数

public Lesson() {
// TODO Auto-generated constructor stub
}

public String getLessonName() {
return lessonName;
}

public void setLessonName(String lessonName) {
this.lessonName = lessonName;
}

public String getLessonScore() {
return lessonScore;
}

public void setLessonScore(String lessonScore) {
this.lessonScore = lessonScore;
}

}

解析student.xml 的方法 :PullXMLTools2.java

package com.pull.parser;

import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.pull.data.Lesson;
import com.pull.data.Student;

public class PullXMLTools2 {

public PullXMLTools2(){
}

public static Set<Student> parseXML(InputStream inputStream , String encode) throws Exception{

Set<Student> students = null;
Student student = null;
Set<Lesson> lessons = null;
Lesson lesson = null;
String currentTag = null;

XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(inputStream, encode);
int eventType = parser.getEventType();

while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
students = new HashSet<Student>();
break;
case XmlPullParser.START_TAG:
currentTag = parser.getName(); //获取当前解析到的开始标签的名称
if ("student".equals(currentTag)) {
student = new Student(); //遇到一个 student开始标签,新建一个Student对象
lessons = new HashSet<Lesson>();
}else if ("name".equals(currentTag)) {
String name = parser.nextText();  //取得student.name的值
student.setName(name);

}else if ("sex".equals(currentTag)) {
String sex = parser.nextText();//取得student.sex的值
student.setSex(sex);
}else if ("lesson".equals(currentTag)) {
lesson = new Lesson();
}else if ("lessonName".equals(currentTag)) {
String lessonName = parser.nextText();
lesson.setLessonName(lessonName);
}else if ("lessonScore".equals(currentTag)) {
String lessonScore = parser.nextText();
lesson.setLessonScore(lessonScore);
}

break;
case XmlPullParser.END_TAG:
currentTag = parser.getName(); //获得当前解析到的关闭标签的名称
if ("lesson".equals(currentTag)) {
lessons.add(lesson);
lesson = null;
}else if ("student".equals(currentTag)) {
student.setLessons(lessons);
lessons = null;
students.add(student);
student = null;
}

break;

}

eventType = parser.next();    //循环方式
}

return students;

}

}

Test2.java   student.xml的测试方法

package com.pull.test;

import java.io.InputStream;
import java.util.Set;

import com.pull.data.Lesson;
import com.pull.data.Student;
import com.pull.http.HttpUtils;
import com.pull.parser.PullXMLTools2;

public class Test2 {

public Test2() {
// TODO Auto-generated constructor stub
}

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub

String path = "http://192.168.0.102:8080/myhttp/student.xml";
InputStream inputStream = HttpUtils.getXML(path);
Set<Student> students = PullXMLTools2.parseXML(inputStream, "utf-8");
for(Student student : students){

System.out.println("Name :"+student.getName());
System.out.println("Sex :"+student.getSex());

Set<Lesson> lessons = student.getLessons();
for(Lesson lesson : lessons){
System.out.println("LessonName :"+lesson.getLessonName());
System.out.println("LessonScore :"+lesson.getLessonScore());
}

System.out.println("-----------------------------");
}
}

}

Weather.java

package com.pull.data;

import java.util.List;

/*
*当前天气信息的类
*
*
* */
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;
}

}

解析weather.xml 的方法 :PullXMLTools3.java

package com.pull.parser;

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

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.pull.data.Forecast;
import com.pull.data.Weather;

public class PullXMLTools3 {

public PullXMLTools3() {
// TODO Auto-generated constructor stub
}

public static Weather parseXML(InputStream inputStream, String encode)
throws Exception {
Weather weather = null;
List<Forecast> forecasts = null;
Forecast forecast = null;

String preTag = null; // 记录之前访问的标签,在需要时作为标记用来判断

XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(inputStream, encode);
int eventType = parser.getEventType();

while (eventType != XmlPullParser.END_DOCUMENT) {

switch (eventType) {

case XmlPullParser.START_TAG:
if ("weather".equals(parser.getName())) {
weather = new Weather();
forecasts = new ArrayList<Forecast>();
} else if ("city".equals(parser.getName())) {
weather.setCity(parser.getAttributeValue(0)); // 设置城市名
} else if ("forecast_date".equals(parser.getName())) {
weather.setForecase_date(parser.getAttributeValue(0)); // 设置预报当天日期
} else if ("current_date_time".equals(parser.getName())) {
weather.setCurrent_date_time(parser.getAttributeValue(0)); // 设置预报当天当时的时间
} else if ("current_conditions".equals(parser.getName())) {
preTag = "current_conditions"; // 设置标记标签
} else if ("condition".equals(parser.getName())
&& "current_conditions".equals(preTag)) {
weather.setCurrent_condition(parser.getAttributeValue(0));// 设置当前的天气
} else if ("humidity".equals(parser.getName())
&& "current_conditions".equals(preTag)) {
weather.setCurrent_humidity(parser.getAttributeValue(0));// 设置当前的湿度
} else if ("icon".equals(parser.getName())
&& "current_conditions".equals(preTag)) {
weather.setCurrent_image_url(parser.getAttributeValue(0)); // 设置当前的气象图标
} else if ("wind_condition".equals(parser.getName())) {
weather.setCurrent_wind(parser.getAttributeValue(0)); // 设置当前的风力情况
} else if ("forecast_conditions".equals(parser.getName())) {
preTag = "forecast_conditions"; // 更改设置 标记标签
forecast = new Forecast();
} else if ("day_of_week".equals(parser.getName())
&& "forecast_conditions".equals(preTag)) {
forecast.setDay_of_week(parser.getAttributeValue(0)); // 设置未来预报周几
} else if ("low".equals(parser.getName())
&& "forecast_conditions".equals(preTag)) {
forecast.setLow(parser.getAttributeValue(0)); // 最低气温
} else if ("high".equals(parser.getName())
&& "forecast_conditions".equals(preTag)) {
forecast.setHigh(parser.getAttributeValue(0)); // 最高气温
} else if ("icon".equals(parser.getName())
&& "forecast_conditions".equals(preTag)) {
forecast.setImage_url(parser.getAttributeValue(0)); // 气象图标
} else if ("condition".equals(parser.getName())
&& "forecast_conditions".equals(preTag)) {
forecast.setCondition(parser.getAttributeValue(0)); // 气象图标
}

break;
case XmlPullParser.END_TAG:
if ("current_conditions".equals(parser.getName())) {
preTag = null;
} else if ("forecast_conditions".equals(parser.getName())) {
forecasts.add(forecast);
forecast = null;
preTag = null;
} else if ("weather".equals(parser.getName())) {
weather.setForecasts(forecasts);
forecasts = null;
}
break;

default:
break;

}

eventType = parser.next();
}

return weather;

}

}


Test3.java  -- 测试weather.xml的方法

package com.pull.test;

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

import com.pull.data.Forecast;
import com.pull.data.Weather;
import com.pull.http.HttpUtils;
import com.pull.parser.PullXMLTools3;

public class Test3 {

public Test3() {
// TODO Auto-generated constructor stub
}

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
InputStream inputStream = HttpUtils.getXML("http://192.168.0.102:8080/myhttp/weather.xml");
Weather weather =PullXMLTools3.parseXML(inputStream, "utf-8");

System.out.println("深圳今天天气预报:\n");
System.out.println("城市 :"+weather.getCity());
System.out.println("当前天气 :"+weather.getCurrent_condition());
System.out.println("当前湿度:"+weather.getCurrent_humidity());
System.out.println("当前风力 :"+weather.getCurrent_wind());
System.out.println("当前图标 :"+weather.getCurrent_image_url());
System.out.println("当前日期 :"+weather.getForecase_date());
System.out.println("当前时间 :"+weather.getCurrent_date_time());
System.out.println("-------------------------------------------");

System.out.println("\n未来几天的天气预报:\n");
List<Forecast> list = weather.getForecasts();
for (Forecast forecast : list) {
System.out.println("日期:"+forecast.getDay_of_week());
System.out.println("天气情况:"+forecast.getCondition());
System.out.println("最低温度:"+forecast.getLow());
System.out.println("最高温度:"+forecast.getHigh());
System.out.println("气象图标:"+forecast.getImage_url());
System.out.println("********************************************");
}

}

}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息