主界面很简单 封装的帮助类传入需要反射的类名 以及xml中的其它参数 得到一个实例化的对象
接下来看看xmlutils
最后主要的逻辑 写在XMLParaserUtil里的:
package com.example.tempand; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import java.lang.reflect.Field; import java.util.HashMap; public class XMLParserUtil<T> extends DefaultHandler{ private StringBuilder text = new StringBuilder(); // 定义变量保存解析结果 public HashMap<String,T> usermap = null; // 定义XML的标签及标签属性名称 public String SAX_ROOT = "config"; public String SAX_LOTTERY = "item"; private final Field[] fields; private Class<T> data; private String index; XMLParserUtil(String index, Class<T> t, String nodename, String rootnode){ fields =t.getDeclaredFields();//通过反射获取类里面的变量 this.data=t; this.index=index; this.SAX_ROOT=rootnode; this.SAX_LOTTERY=nodename; } public HashMap<String,T> getUsermap(){ return usermap; } @Override public void startDocument() throws SAXException { // TODO Auto-generated method stub super.startDocument(); } @Override public void endDocument() throws SAXException { // TODO Auto-generated method stub super.endDocument(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // TODO Auto-generated method stub super.startElement(uri, localName, qName, attributes); if (localName.equalsIgnoreCase(SAX_ROOT)) {// 根元素 if (null == usermap) { usermap = new HashMap<String, T>(); } else { usermap.clear(); } } else if (localName.equalsIgnoreCase(SAX_LOTTERY)) { try { T obj = data.newInstance(); for (int i = 0; i < fields.length; i++) { fields[i].getName(); String value = attributes.getValue(fields[i].getName()); fields[i].setAccessible(true); if (null!=value&&!"".equals(value)) fields[i].set(obj,value); //给变量付值 } usermap.put(attributes.getValue(index),obj); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } else { // Nothing to do ... } } @Override public void characters(char[] ch, int start, int length) throws SAXException { // TODO Auto-generated method stub super.characters(ch, start, length); text.setLength(0); text.append(String.valueOf(ch, start, length)); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { // TODO Auto-generated method stub super.endElement(uri, localName, qName); if (localName.equalsIgnoreCase(SAX_ROOT)) {// 根元素 //nothing } // } }