前一阵做了一个XML解析方法,是使用SAX和XMLPull解析xml为一个类似于Dom节点的对象。解析式成功的但是发现使用起来不是很方便,于是乎对Data增加了
几个获取子节点和属性的方法,修改完后用起来还算方便。后来想增加一个XML映射成对象的方法,在网上找了些都不够通用,于是乎自己写了一个映射方法,
还算通用。
首先贴下 Data对象 这个是xml解析后的结果对象
package com.popo; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; /** * * @author liboliu * */ public class Data { public String name = null; public String data = null; public HashMap<String,String> attr = null; public HashMap<String,ArrayList<Data>> son = null; public ArrayList<Data> getSonData(String key) { return (ArrayList<Data>) (son == null ? son : son.get(key)); } public Object getAttr(String key) { return attr.get(key); } public Data getSon(String key) { ArrayList<Data> sondata = son.get(key); return sondata.get(0); } public Data getSon(String key,int index) { ArrayList<Data> sondata = son.get(key); return sondata.get(index); } // //对象翻译为XML @Override public String toString() { // TODO Auto-generated method stub StringBuilder sb = new StringBuilder(); // node名字 sb.append("<" + name + ""); if (attr != null) { Set<String> keys = attr.keySet(); Iterator<String> it = keys.iterator(); while (it.hasNext()) { String key_ = it.next(); sb.append(" " + key_ + "=" + attr.get(key_) + " "); } } sb.append(" >\n"); if (son != null) { Set<String> keys = son.keySet(); Iterator<String> it = keys.iterator(); while (it.hasNext()) { String key_ = it.next(); ArrayList<Data> sonData = son.get(key_); for (Data d : sonData) { sb.append(d); } } } if (data != null) { sb.append(data + "\n"); } // 结束 sb.append("</" + name + ">\n"); return sb.toString(); } @SuppressWarnings("unchecked") public <T> T toObject(Class<T> clazz,Object parent) throws InstantiationException,IllegalAccessException,SecurityException,NegativeArraySizeException,ClassNotFoundException,IllegalArgumentException,InvocationTargetException { String name = clazz.getName(); T o = null; if (name.contains("$")) { Constructor<?> constructor = (clazz.getConstructors())[0]; o = (T) constructor.newInstance(parent); } else { if(!isBaseType(clazz)) o = clazz.newInstance(); } if (attr != null) { Set<String> keys = attr.keySet(); for (String key : keys) { String value = attr.get(key); if (value == null) continue; setValue(o,clazz,key,value); } } if (son != null) { Set<String> sonKeys = son.keySet(); for (String sonKey : sonKeys) { Field sonField = null; try { sonField = clazz.getField(sonKey); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (sonField == null) continue; ArrayList<Data> sonList = son.get(sonKey); String className = sonField.getType().getName(); if (className.startsWith("[L")) { int size = sonList.size(); String sonFieldClassName = className.substring(2,className.length() - 1); Object[] sonArray = (Object[]) Array.newInstance( Class.forName(sonFieldClassName),size); for (int i = 0; i < size; i++) { sonArray[i] = sonList.get(i).toObject( Class.forName(sonFieldClassName),o); } sonField.set(o,sonArray); } else { Data sonData = sonList.get(0); Object sonObject = sonData.toObject(sonField.getType(),o); if (sonObject != null) { sonField.set(o,sonObject); } } } } if (data != null) { Field sonField = null; if (attr == null || attr.size() == 0) { if (isBaseType(clazz)) { try { sonField = parent.getClass().getField(this.name); if (sonField != null) { setValue(parent,parent.getClass(),this.name,data); } } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } } try { sonField = clazz.getField(name); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (sonField != null) { setValue(o,name,data); } } return o; } public <T> boolean isBaseType(Class<T> clazz) { if (clazz == String.class || clazz == Integer.TYPE || clazz == Float.TYPE || clazz == Double.TYPE || clazz == Long.TYPE || clazz == Short.TYPE || clazz == Byte.TYPE || clazz == Character.TYPE) { return true; } else { return false; } } private void setValue(Object p,Class clazz,String ff,String data2) throws SecurityException,IllegalAccessException { // TODO Auto-generated method stub Field f = null; try { f = clazz.getField(ff); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (f == null) return; Class<?> t = f.getType(); if (t == String.class) { f.set(p,data2); } else if (t == Integer.TYPE) { f.set(p,Integer.parseInt(data2)); } else if (t == Float.TYPE) { f.set(p,Float.parseFloat(data2)); } else if (t == Double.TYPE) { f.set(p,Double.parseDouble(data2)); } else if (t == Long.TYPE) { f.set(p,Long.parseLong(data2)); } else if (t == Short.TYPE) { f.set(p,Short.parseShort(data2)); } else if (t == Boolean.TYPE) { f.set(p,Boolean.parseBoolean(data2)); } else if(t==Byte.TYPE) { f.set(p,Byte.parseByte(data2)); }else{ f.set(p,data2); } } }
然后贴下使用XmlPull解析的例子
public Data parXml(InputStream in) throws XmlPullParserException { LinkedList<Data> stack = null; Data parent = null; Data self = null; Data root = null; String rootTag=null; try { XmlPullParserFactory f = XmlPullParserFactory.newInstance(); f.setNamespaceAware(true); XmlPullParser xmlPullParser = f.newPullParser(); xmlPullParser.setInput(new InputStreamReader(in)); StringBuilder tab = new StringBuilder(); int eventType = xmlPullParser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_DOCUMENT) { root = new Data(); stack = new LinkedList<Data>(); stack.addFirst(root); } else if (eventType == XmlPullParser.START_TAG) { self = new Data(); self.name = xmlPullParser.getName(); if(rootTag==null) rootTag=self.name; parent = stack.peekFirst(); stack.addFirst(self); addSelfInParent(self,parent,xmlPullParser.getName()); int count = xmlPullParser.getAttributeCount(); if (count > 0) { self.attr = new HashMap<String,String>(); for (int i = 0; i < count; i++) { self.attr.put(xmlPullParser.getAttributeName(i),xmlPullParser.getAttributeValue(i)); } } } else if (eventType == XmlPullParser.END_TAG) { stack.removeFirst(); self = stack.getFirst(); } else if (eventType == XmlPullParser.TEXT) { if (self != null) self.data = xmlPullParser.getText(); } try { eventType = xmlPullParser.next(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } stack = null; parent = null; self = null; } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } return root.getSon(rootTag); }
使用方法小例子
new Thread() { public void run() { URL url; try { url = new URL( "http://www.w3school.com.cn/example/xmle/plant_catalog.xml"); InputStream in = url.openConnection().getInputStream(); Data d = parXml(in); Catalog p = d.toObject(Catalog.class,null); Log.v("helll","xixix"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NegativeArraySizeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } }; }.start();
反射的对象解构
public class Catalog { public Plant[] PLANT; public class Plant { public String COMMON; public String BOTANICAL; public String ZONE; public String LIGHT; public String PRICE; public String AVAILABILITY; } }原文链接:https://www.f2er.com/xml/300000.html