浅谈XML的封装与解析

2015-08-09 14:50 阅读 3,570 次 评论 0 条
版权声明:本文著作权归TeachCourse所有,未经许可禁止转载,谢谢支持!
转载请注明出处:http://teachcourse.cn/293.html

第一种方式:

<?xml version="1.0" encoding="utf-8"?>
<list>

<student id="num1">
<name>张三</name>
<age>24</age>
<address>http://teachcourse.cn</address>
</student>

<student id="num2">
<name>李四</name>
<age>24</age>
<address>http://teachcourse.cn</address>
</student>

<student>
<id>num3</id>
<name>王五</name>
<age>24</age>
<address>http://teachcourse.cn</address>
</student>

</list>

 

[java][/java]

public class User{

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

public void setId(int id){
this.id=id;
}
public int getId(){
return id;
}

public void setAge(int age){
this.age=age;
}
public int getAge(){
return age;
}

public void setAddress(String address){
this.address=address;
}
public String getAddress(){
return address;
}

public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}

}

 

第二种方式:

<?xml version="1.0" encoding="utf-8"?>
<course id="num1" name="Java课程">

<address>多功能楼201</address>

</course>

 

[java][/java]

public class Course{

private int id;
private String name;
private String address;

public void setId(int id){
this.id=id;
}
public int getId(){
return id;
}

public void setAddress(String address){
this.address=address;
}
public String getAddress(){
return address;
}

public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}

}

 

第三种方式:

<?xml version="1.0" encoding="utf-8"?>

<parent>

<total>3</total>

<list>

<student id="num1">
<name>张三</name>
<age>24</age>
<address>http://teachcourse.cn</address>
</student>

<student id="num2">
<name>李四</name>
<age>24</age>
<address>http://teachcourse.cn</address>
</student>

<student>
<id>num3</id>
<name>王五</name>
<age>24</age>
<address>http://teachcourse.cn</address>
</student>

</list>

</parent>

[java][/java]

public class UserList{

private String total;

private List<User> userList;

public void setTotal(String total){

this.total=total;

}

public String getTotal(){

return total;

}

public void setList<User>(List<User> userList){

this.userList=userList;

}

public String getList<User>(){

return userList;

}
}

 

 

对以上三种XML文件适用的解析如下:

[java][/java]

import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;

import android.util.Log;
import android.util.Xml;

/**
* 对pull解析xml进行了封装,不用给每个xml,再创建一个解析类
*
* @author dazhao
*
* http://www.teachcourse.cn/
*
*/
public class XmlParse {

/**
* 解析XML
* @param is        xml字节流
* @param clazz     字节码      如:Object.class
* @param startName       开始位置
* @return          返回List列表
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public List getXmlList(InputStream is, Class<?> clazz, String startName) {
List list = null;
XmlPullParser parser = Xml.newPullParser();
Object object = null;
try {
parser.setInput(is, "UTF-8");
//事件类型
int eventType = parser.getEventType();

while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
list = new ArrayList<Object>();
break;
case XmlPullParser.START_TAG:
//获得当前节点元素的名称
String name = parser.getName();
if (startName.equals(name)) {
object = clazz.newInstance();
//判断标签里是否有属性,如果有,则全部解析出来
int count = parser.getAttributeCount();
for(int i=0; i<count; i++)
setXmlValue(object, parser.getAttributeName(i), parser.getAttributeValue(i));
} else if (object != null) {
setXmlValue(object, name, parser.nextText());
}
break;
case XmlPullParser.END_TAG:
if (startName.equals(parser.getName())) {
list.add(object);
object = null;
}
break;
}
eventType = parser.next();
}
} catch (Exception e) {
Log.e("xml pull error", e.toString());
}
return list;
}

/**
* 解析XML
* @param is        xml字节流
* @param clazz     字节码      如:Object.class
* @return          返回Object
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object getXmlObject(InputStream is, Class<?> clazz) {
XmlPullParser parser = Xml.newPullParser();
Object object = null;
List list = null;
Object subObject = null;
String subName = null;
try {
parser.setInput(is, "UTF-8");
//事件类型
int eventType = parser.getEventType();

while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
object = clazz.newInstance();
break;
case XmlPullParser.START_TAG:
//获得当前节点元素的名称
String name = parser.getName();

Field[] f = null;
if(subObject == null){
f = object.getClass().getDeclaredFields();

//判断标签里是否有属性,如果有,则全部解析出来
int count = parser.getAttributeCount();
for(int j=0; j<count; j++)
setXmlValue(object, parser.getAttributeName(j), parser.getAttributeValue(j));
}else{
f = subObject.getClass().getDeclaredFields();
}

for(int i = 0; i < f.length; i++){
if(f[i].getName().equalsIgnoreCase(name)){
//判断是不是List类型
if(f[i].getType().getName().equals("java.util.List")){
Type type = f[i].getGenericType();
if (type instanceof ParameterizedType) {
//获得泛型参数的实际类型
Class<?> subClazz = (Class<?>)((ParameterizedType)type).getActualTypeArguments()[0];
subObject = subClazz.newInstance();
subName = f[i].getName();

//判断标签里是否有属性,如果有,则全部解析出来
int count = parser.getAttributeCount();
for(int j=0; j<count; j++)
setXmlValue(subObject, parser.getAttributeName(j), parser.getAttributeValue(j));

if(list == null){
list = new ArrayList<Object>();
f[i].setAccessible(true);
f[i].set(object, list);
}
}
}else{   //普通属性
if(subObject != null){
setXmlValue(subObject, name, parser.nextText());
}else{
setXmlValue(object, name, parser.nextText());
}
}
break;
}
}
break;
case XmlPullParser.END_TAG:
if (subObject != null && subName.equalsIgnoreCase(parser.getName())) {
list.add(subObject);
subObject = null;
subName = null;
}
break;
}
eventType = parser.next();
}
} catch (Exception e) {
Log.e("xml pull error", e.getMessage());
}
return object;
}

/**
* 把xml标签的值,转换成对象里属性的值
* @param  t    对象
* @param name   xml标签名
* @param value  xml标签名对应的值
*/
private void setXmlValue(Object t, String name, String value){
try {
Field[] f = t.getClass().getDeclaredFields();
for(int i = 0; i < f.length; i++){
if(f[i].getName().equalsIgnoreCase(name)){
f[i].setAccessible(true);
//获得属性类型
Class<?> fieldType = f[i].getType();

if(fieldType == String.class) {
f[i].set(t, value);
}else if(fieldType == Integer.TYPE) {
f[i].set(t, Integer.parseInt(value));
}else if(fieldType == Float.TYPE) {
f[i].set(t, Float.parseFloat(value));
}else if(fieldType == Double.TYPE) {
f[i].set(t, Double.parseDouble(value));
}else if(fieldType == Long.TYPE) {
f[i].set(t, Long.parseLong(value));
}else if(fieldType == Short.TYPE) {
f[i].set(t, Short.parseShort(value));
}else if(fieldType == Boolean.TYPE) {
f[i].set(t, Boolean.parseBoolean(value));
}else{
f[i].set(t, value);
}
}
}
} catch (Exception e) {
Log.e("xml error", e.toString());
}
}

}

关注公众号 扫一扫二维码,加我QQ

如果文章对你有帮助,欢迎点击上方按钮关注作者

来源:TeachCourse每周一次,深入学习Android教程,关注(QQ1589359239或公众号TeachCourse)
转载请注明出处:http://teachcourse.cn/293.html
”Found 2 version of android-support-v4.jar in the dependency list“解决思路 ”Found 2 version of android-
如何自定义View视图控件案例开发(一) 如何自定义View视图控件案例开发
浅谈ContentValues类 浅谈ContentValues类
关于Android项目中R文件缺失的解决办法 关于Android项目中R文件缺失的

发表评论

呲牙 憨笑 坏笑 偷笑 色 微笑 抓狂 睡觉 酷 流汗 鼓掌 大哭 可怜 疑问 晕 惊讶 得意 尴尬 发怒 奋斗 衰 骷髅 啤酒 吃饭 礼物 强 弱 握手 OK NO 勾引 拳头 差劲 爱你

表情