android 反射解析xml文件成为java对象
ReflectResolveXML.java
package com.player.handle;import java.lang.reflect.Field;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Collection;import java.util.Date;import java.util.Stack;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;public class ReflectResolveXML extends DefaultHandler {public static final String T_COLLECTION="collection";public static final String T_OBJECT="object";public static final String T_LANG="lang";private static final String T_DATE = "date";private static final String D_PATTERN = "yyyy-MM-dd HH:mm:ss";Stack<Object> stack=new Stack<Object>();private Object root=null;public Object getRoot() {return root;}@Overridepublic void endElement(String uri, String localName, String qName)throws SAXException {//System.out.println("endElement:"+uri+" localName:"+localName+ " qName:"+qName);if (qName.equals(T_OBJECT)||qName.equals(T_COLLECTION)) {//如果集合类或者object类 属性注入完成则需要弹出堆栈stack.pop();}}@Overridepublic void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {// TODO Auto-generated method stuStringBuffer stb=new StringBuffer();for (int i = 0; i < attributes.getLength(); i++) {stb.append(attributes.getValue(i)+"---");}System.out.println("startElement:"+uri+" localName:"+localName+ " qName:"+qName+" Attr: "+stb.toString());//如果根元素为null 则新建一个 因为第一个读取的必定是根元素String type=attributes.getValue("type");if (root==null) {root=instanceObjectByType(type); stack.push(root);return;}String value=attributes.getValue("value");String name=attributes.getValue("name");Object pObj=stack.peek();//根元素不为空 则根据 qname判断 if (qName.equals(T_COLLECTION)||qName.equals(T_OBJECT)) {//如果是list则new 一个list 或者 object 则new出来Object obj=instanceObjectByType(type);stack.push(obj);injectToParent(pObj, obj,name);}else if (qName.equals(T_LANG)) {//如果是lang 则需要转化value值Object valueObj=typeConvert(type, value);injectToParent(pObj,valueObj,name);}else if (qName.equals(T_DATE)) {//如果是dateString pattern=attributes.getValue("pattern");if (pattern==null) {pattern=D_PATTERN;}Object valueObj=typeConvertDate(value,pattern);injectToParent(pObj,valueObj,name);}}//转化date类型private Date typeConvertDate( String value, String pattern) {SimpleDateFormat sdf=new SimpleDateFormat(pattern);Date date;try {date = sdf.parse(value);return date;} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}//向上一级元素中注入属性 或者向集合类中add子元素private void injectToParent(Object pObj, Object fieldValue ,String fieldName) {if (pObj instanceof Collection) {//如果上一级是集合类 则需要添加进去((Collection) pObj).add(fieldValue);return ;}//如果上一级是object 则需要反射字段赋值Field[] fields = pObj.getClass().getDeclaredFields();for (Field field : fields) {if (field.getName().equals(fieldName)) {try {field.setAccessible(true);field.set(pObj, fieldValue);} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();}break;}}}//反射实例化对象private Object instanceObjectByType(String qName) {try {Class localClass= Class.forName(qName);Object obj=localClass.getConstructor().newInstance();return obj; } catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();throw new RuntimeException(e);}}// 此方法用于将一个字符串转换为相应的数据类型public Object typeConvert(String className, String value) {if (className.equals("java.lang.String")) {return value;} else if (className.equals("java.lang.Integer")) {return Integer.valueOf(value);} else if (className.equals("java.lang.Long")) {return Long.valueOf(value);} else if (className.equals("java.lang.Boolean")) {return Boolean.valueOf(value);} else if (className.equals("java.lang.Float")) {return Float.valueOf(value);} else if (className.equals("java.lang.Double")) {return Double.valueOf(value);} elsereturn null;} }
?reflect.xml文件
<?xml version="1.0" encoding="UTF-8"?><collecton type="java.util.ArrayList"><object type="com.player.module.Resource"><lang type="java.lang.String" name="id" value="0001"></lang><object type="com.player.module.Mp3" name="mp3"><lang type="java.lang.String" name="mp3Name" value="天地初开的时候.mp3"></lang><lang type="java.lang.Integer" name="mp3Size" value="12333"></lang></object><object type="com.player.module.Lrc" name="lrc"><lang type="java.lang.String" name="lrcName" value="天地初开的时候.lrc"></lang><lang type="java.lang.Integer" name="lrcSize" value="4312"></lang></object><date type="java.util.Date" name="date" value="2001-12-12 12:12:12"></date></object><object type="com.player.module.Resource"><lang type="java.lang.String" name="id" value="0002"></lang><object type="com.player.module.Mp3" name="mp3"><lang type="java.lang.String" name="mp3Name" value="那一曲盛放的玫瑰.mp3"></lang><lang type="java.lang.Integer" name="mp3Size" value="12333"></lang></object><object type="com.player.module.Lrc" name="lrc"><lang type="java.lang.String" name="lrcName" value="那一曲盛放的玫瑰.lrc"></lang><lang type="java.lang.Integer" name="lrcSize" value="4312"></lang></object><date type="java.util.Date" name="date" value="2001-12-13 12:12:12"></date></object></collecton>
?HandleTest.java
package com.player.handle;import java.io.File;import java.io.IOException;import java.util.List;import javax.xml.parsers.ParserConfigurationException;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import org.junit.Test;import org.xml.sax.SAXException;import com.player.module.Resource;public class HandleTest {@Testpublic void testresolveXmlTest() throws ParserConfigurationException, SAXException, IOException{//HttpDownloader downloader=new HttpDownloader();//String xml= downloader.download(Mp3ListActiviy.URL);File file=new java.io.File("D:\\Soft\\Program\\Apache-Tomcat-6.0.20\\webapps\\android_mp3\\reflect.xml");SAXParser saxParser=SAXParserFactory.newInstance().newSAXParser();ReflectResolveXML reflectResolveXML=new ReflectResolveXML();saxParser.parse(file, reflectResolveXML);List<Resource> resources=(List<Resource>) reflectResolveXML.getRoot();System.out.println("---------------------");for (Resource resource : resources) {System.out.println(resource.toString());}//mp3xmlHandle.getMp3List();}}
?三个javabean
public class Lrc {private String lrcName;private Integer lrcSize;}public class Mp3 {private String mp3Name;private int mp3Size;}public class Resource {private String id;private Mp3 mp3;private Lrc lrc;private Date date;}?