Java XML解析,,Node直接转为对象。考虑了一般的类,简单类型,数组,还未考虑List,Map

XML解析类
  1 package com.supermap.services.components.tilecache.convert;
  2 
  3 import java.lang.reflect.Array;
  4 import java.util.ArrayList;
  5 import java.util.List;
  6 
  7 import org.w3c.dom.Element;
  8 import org.w3c.dom.Node;
  9 import org.w3c.dom.NodeList;
 10 import org.w3c.dom.Text;
 11 
 12 public class XMLUtil {
 13 
 14     /**
 15      * 得到第一个非文本的节点
 16      * 
 17      * @param node
 18      * @return
 19      */
 20     public static Node getFirstNode(Node node) {
 21         NodeList nodelist = node.getChildNodes();
 22         for (int i = 0; i < nodelist.getLength(); i++) {
 23             Node childNode = nodelist.item(i);
 24             if (childNode instanceof Text) {
 25                 continue;
 26             }
 27             return childNode;
 28         }
 29         return null;
 30     }
 31 
 32     /**
 33      * 得到节点下Tag为name的节点
 34      * 
 35      * @param node
 36      * @param name
 37      * @return
 38      */
 39     public static Node getNodeByTagName(Node node, String name) {
 40         Element elem = (Element) node;
 41         return elem.getElementsByTagName(name).item(0);
 42     }
 43 
 44     /**
 45      * 得到节点下Tag为name的节点集合
 46      * 
 47      * @param node
 48      * @param name
 49      * @return 节点集合
 50      */
 51     public static List<Node> getNodesByTagName(Node node, String name) {
 52         Element elem = (Element) node;
 53         NodeList nodelist = elem.getElementsByTagName(name);
 54         List<Node> result = new ArrayList<Node>();
 55         for (int i = 0; i < nodelist.getLength(); i++) {
 56             result.add(nodelist.item(i));
 57         }
 58         return result;
 59     }
 60 
 61     /**
 62      * 判断节点是否为文本节点 <a>string</a> 就是文本节点
 63      * 
 64      * @param node
 65      * @return
 66      */
 67     public static Boolean isTextNode(Node node) {
 68         NodeList childs = node.getChildNodes();
 69         if (childs.getLength() == 1) {
 70             Node child = childs.item(0);
 71             if (child instanceof Text) {
 72                 return true;
 73             }
 74         }
 75         return false;
 76     }
 77 
 78     /**
 79      * 节点非文本节点的集合
 80      * 
 81      * @return
 82      */
 83     public static List<Node> getChildsNodes(Node node) {
 84         NodeList nodelist = node.getChildNodes();
 85         List<Node> result = new ArrayList<Node>();
 86         for (int i = 0; i < nodelist.getLength(); i++) {
 87             Node child = nodelist.item(i);
 88             if (child instanceof Text) {
 89                 continue;
 90             }
 91             result.add(child);            
 92         }
 93         return result;
 94     }
 95 
 96     @SuppressWarnings("unchecked")
 97     /**
 98      * 把node转成type类型的对象
 99      * @param node
100      * @param type
101      * @return
102      */
103     public static <T> T nodeToObject(Node node, Class<?> type) {
104         Object obj = null;
105         if (type.isArray()) {// 考虑数组
106             Class<?> itemType = type.getComponentType();//级数元素类型
107             List<Node> childs = getChildsNodes(node);
108             Object array= Array.newInstance(itemType, childs.size());
109             for(int i =0;i<childs.size();i++){
110                 Node childNode = childs.get(i);
111                 Object childValue = nodeToObject(childNode,itemType);
112                 Array.set(array, i, childValue);
113             }
114             return (T) array;            
115         }
116         if(type.isPrimitive()){//如果是简单类型
117             return (T) ReflectionUtil.getValue(type, node.getTextContent());
118         }
119         //list类型
120         try {
121             obj = type.newInstance();//一般意义的类了
122         } catch (Exception e) {
123             e.printStackTrace();
124             return (T) obj;
125         }
126         NodeList childs = node.getChildNodes();
127         for (int i = 0; i < childs.getLength(); i++) {
128             Node child = childs.item(i);
129             if (child instanceof Text) {
130                 continue;
131             }
132             String nodeName = child.getNodeName();
133             try {
134                 if (isTextNode(child)) {// 如果是文本类的
135                     ReflectionUtil.setPropertyValue(obj, nodeName,
136                             child.getTextContent());
137                 } else {
138                     Class<?> propType = ReflectionUtil.getPropertyType(obj,
139                             nodeName);
140                     if (propType != null) {
141                         Object childValue = nodeToObject(child, propType);
142                         ReflectionUtil.setPropertyValue(obj, nodeName,
143                                 childValue);
144                     }
145                 }
146             } catch (Exception ex) {
147                 ex.printStackTrace();
148             }
149 
150         }
151         return (T) obj;
152     }
153 
154 }
反射类
  1 package com.supermap.services.components.tilecache.convert;
  2 
  3 import java.beans.BeanInfo;
  4 import java.beans.IntrospectionException;
  5 import java.beans.Introspector;
  6 import java.beans.PropertyDescriptor;
  7 import java.lang.reflect.InvocationTargetException;
  8 
  9 import com.supermap.services.components.commontypes.OutputFormat;
 10 
 11 
 12 public class ReflectionUtil {
 13     
 14     /**
 15      * 给属性赋值[默认包括了字段]
 16      * @param obj
 17      * @param proName
 18      * @param value
 19      * @throws IntrospectionException 
 20      * @throws InvocationTargetException 
 21      * @throws IllegalAccessException 
 22      * @throws IllegalArgumentException 
 23      */
 24     public static void setPropertyValue(Object obj,String proName,Object value) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
 25          BeanInfo beanInfo= Introspector.getBeanInfo(obj.getClass());
 26          for(PropertyDescriptor prop : beanInfo.getPropertyDescriptors()){
 27              if(prop.getName().equals(proName)){
 28                  Class<?> propType =prop.getReadMethod().getReturnType();
 29                  Object porpvalue = getValue(propType, value);
 30                  prop.getWriteMethod().invoke(obj, porpvalue);
 31                  return ;
 32              }
 33          }
 34          
 35          for(java.lang.reflect.Field field : obj.getClass().getFields()){
 36              if( field.getName().equals(proName)){
 37                  Object filedValue= getValue(field.getType(),value);    
 38                  field.set(obj, filedValue);            
 39                  return ;
 40              }
 41          }
 42     }
 43     
 44     /**
 45      * 得到属性的类别
 46      * @param obj
 47      * @param proName
 48      * @return 
 49      * @throws IntrospectionException 
 50      */
 51     public static Class<?> getPropertyType(Object obj,String proName) throws IntrospectionException{
 52          BeanInfo beanInfo= Introspector.getBeanInfo(obj.getClass());
 53          for(PropertyDescriptor prop : beanInfo.getPropertyDescriptors()){
 54              if(prop.getName().equals(proName)){
 55                 return prop.getReadMethod().getReturnType();
 56              }
 57          }         
 58          for(java.lang.reflect.Field field : obj.getClass().getFields()){
 59              if( field.getName().equals(proName)){
 60                  return field.getType();
 61              }
 62          }
 63          return null;
 64     }
 65     
 66     /**
 67      * 把obj转成type类型
 68      * @param type
 69      * @param obj
 70      * @return
 71      */
 72     public static Object getValue(Class<?> type,Object obj){
 73         String className = type.getName();
 74         if(obj.getClass() == type){
 75             return obj;
 76         }
 77         if(type .equals(Double.class) ||className=="double"){
 78             return Double.parseDouble(obj.toString());
 79         }
 80         if(type==Float.class||className=="float"){
 81             return Float.parseFloat(obj.toString());
 82         }
 83         if(type==Integer.class||className=="int"){
 84             return Integer.parseInt(obj.toString());
 85         }
 86         if(type.equals( String.class)||className=="string"){
 87             return obj.toString();
 88         }
 89         if(type.equals(Boolean.class)||className=="boolean"){
 90             return Boolean.parseBoolean(obj.toString());
 91         }
 92         if(type.isEnum()){
 93             Class<?>[] params = new Class<?>[1];
 94             params[0] = String.class;
 95             try {
 96                 return type.getDeclaredMethod("valueOf", params).invoke(null, obj.toString());
 97             } catch (SecurityException e) {
 98                 e.printStackTrace();
 99             } catch (NoSuchMethodException e) {
100                 e.printStackTrace();
101             } catch (IllegalArgumentException e) {
102                 e.printStackTrace();
103             } catch (IllegalAccessException e) {
104                 e.printStackTrace();
105             } catch (InvocationTargetException e) {
106                 e.printStackTrace();
107             }
108         }
109         //if(type.equals(Enum))
110         return null;
111     }
112     
113     public static void main(String[] argc){
114         OutputFormat format = OutputFormat.BINARY;
115         //OutputFormat.valueOf(name)
116         //format.valueOf(name)
117         OutputFormat myEnum= (OutputFormat) getValue(format.getClass(),"BINARY");
118         System.out.println(format.toString());
119     }
120 }

 

 

posted @ 2012-04-23 15:28  如坐夕阳  Views(1567)  Comments(0Edit  收藏  举报