主界面很簡單 封裝的幫助類傳入需要反射的類名 以及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 } // } }