`

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

 
阅读更多
XML解析类
 package com.supermap.services.components.tilecache.convert;
 
 import java.lang.reflect.Array;
 import java.util.ArrayList;
 import java.util.List;
 
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 import org.w3c.dom.Text;
 
 public class XMLUtil {
 
     /**
      * 得到第一个非文本的节点
      * 
      * @param node
      * @return
      */
     public static Node getFirstNode(Node node) {
         NodeList nodelist = node.getChildNodes();
         for (int i = 0; i < nodelist.getLength(); i++) {
             Node childNode = nodelist.item(i);
             if (childNode instanceof Text) {
                 continue;
             }
             return childNode;
         }
         return null;
     }
 
     /**
      * 得到节点下Tag为name的节点
      * 
      * @param node
      * @param name
      * @return
      */
     public static Node getNodeByTagName(Node node, String name) {
         Element elem = (Element) node;
         return elem.getElementsByTagName(name).item(0);
     }
 
     /**
      * 得到节点下Tag为name的节点集合
      * 
      * @param node
      * @param name
      * @return 节点集合
      */
     public static List<Node> getNodesByTagName(Node node, String name) {
         Element elem = (Element) node;
         NodeList nodelist = elem.getElementsByTagName(name);
         List<Node> result = new ArrayList<Node>();
         for (int i = 0; i < nodelist.getLength(); i++) {
             result.add(nodelist.item(i));
         }
         return result;
     }
 
     /**
      * 判断节点是否为文本节点 <a>string</a> 就是文本节点
      * 
      * @param node
      * @return
      */
     public static Boolean isTextNode(Node node) {
         NodeList childs = node.getChildNodes();
         if (childs.getLength() == 1) {
             Node child = childs.item(0);
             if (child instanceof Text) {
                 return true;
             }
         }
         return false;
     }
 
     /**
      * 节点非文本节点的集合
      * 
      * @return
      */
     public static List<Node> getChildsNodes(Node node) {
         NodeList nodelist = node.getChildNodes();
         List<Node> result = new ArrayList<Node>();
         for (int i = 0; i < nodelist.getLength(); i++) {
             Node child = nodelist.item(i);
             if (child instanceof Text) {
                 continue;
             }
             result.add(child);            
         }
         return result;
     }
 
     @SuppressWarnings("unchecked")
     /**
      * 把node转成type类型的对象
      * @param node
      * @param type
      * @return
      */
     public static <T> T nodeToObject(Node node, Class<?> type) {
         Object obj = null;
         if (type.isArray()) {// 考虑数组
             Class<?> itemType = type.getComponentType();//级数元素类型
             List<Node> childs = getChildsNodes(node);
             Object array= Array.newInstance(itemType, childs.size());
             for(int i =0;i<childs.size();i++){
                 Node childNode = childs.get(i);
                 Object childValue = nodeToObject(childNode,itemType);
                 Array.set(array, i, childValue);
             }
             return (T) array;            
         }
         if(type.isPrimitive()){//如果是简单类型
             return (T) ReflectionUtil.getValue(type, node.getTextContent());
         }
         //list类型
         try {
             obj = type.newInstance();//一般意义的类了
         } catch (Exception e) {
             e.printStackTrace();
             return (T) obj;
         }
         NodeList childs = node.getChildNodes();
         for (int i = 0; i < childs.getLength(); i++) {
             Node child = childs.item(i);
             if (child instanceof Text) {
                 continue;
             }
             String nodeName = child.getNodeName();
             try {
                 if (isTextNode(child)) {// 如果是文本类的
                     ReflectionUtil.setPropertyValue(obj, nodeName,
                             child.getTextContent());
                 } else {
                     Class<?> propType = ReflectionUtil.getPropertyType(obj,
                             nodeName);
                     if (propType != null) {
                         Object childValue = nodeToObject(child, propType);
                         ReflectionUtil.setPropertyValue(obj, nodeName,
                                 childValue);
                     }
                 }
             } catch (Exception ex) {
                 ex.printStackTrace();
             }
 
         }
         return (T) obj;
     }
 
 }


==============================================

反射类
 package com.supermap.services.components.tilecache.convert;
 
 import java.beans.BeanInfo;
 import java.beans.IntrospectionException;
 import java.beans.Introspector;
 import java.beans.PropertyDescriptor;
 import java.lang.reflect.InvocationTargetException;
 
 import com.supermap.services.components.commontypes.OutputFormat;
 
 
 public class ReflectionUtil {
     
     /**
      * 给属性赋值[默认包括了字段]
      * @param obj
      * @param proName
      * @param value
      * @throws IntrospectionException 
      * @throws InvocationTargetException 
      * @throws IllegalAccessException 
      * @throws IllegalArgumentException 
      */
     public static void setPropertyValue(Object obj,String proName,Object value) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
          BeanInfo beanInfo= Introspector.getBeanInfo(obj.getClass());
          for(PropertyDescriptor prop : beanInfo.getPropertyDescriptors()){
              if(prop.getName().equals(proName)){
                  Class<?> propType =prop.getReadMethod().getReturnType();
                  Object porpvalue = getValue(propType, value);
                  prop.getWriteMethod().invoke(obj, porpvalue);
                  return ;
              }
          }
          
          for(java.lang.reflect.Field field : obj.getClass().getFields()){
              if( field.getName().equals(proName)){
                  Object filedValue= getValue(field.getType(),value);    
                  field.set(obj, filedValue);            
                  return ;
              }
          }
     }
     
     /**
      * 得到属性的类别
      * @param obj
      * @param proName
      * @return 
      * @throws IntrospectionException 
      */
     public static Class<?> getPropertyType(Object obj,String proName) throws IntrospectionException{
          BeanInfo beanInfo= Introspector.getBeanInfo(obj.getClass());
          for(PropertyDescriptor prop : beanInfo.getPropertyDescriptors()){
              if(prop.getName().equals(proName)){
                 return prop.getReadMethod().getReturnType();
              }
          }         
          for(java.lang.reflect.Field field : obj.getClass().getFields()){
              if( field.getName().equals(proName)){
                  return field.getType();
              }
          }
          return null;
     }
     
     /**
      * 把obj转成type类型
      * @param type
      * @param obj
      * @return
      */
     public static Object getValue(Class<?> type,Object obj){
         String className = type.getName();
         if(obj.getClass() == type){
             return obj;
         }
         if(type .equals(Double.class) ||className=="double"){
             return Double.parseDouble(obj.toString());
         }
         if(type==Float.class||className=="float"){
             return Float.parseFloat(obj.toString());
         }
         if(type==Integer.class||className=="int"){
             return Integer.parseInt(obj.toString());
         }
         if(type.equals( String.class)||className=="string"){
             return obj.toString();
         }
         if(type.equals(Boolean.class)||className=="boolean"){
             return Boolean.parseBoolean(obj.toString());
         }
         if(type.isEnum()){
             Class<?>[] params = new Class<?>[1];
             params[0] = String.class;
             try {
                 return type.getDeclaredMethod("valueOf", params).invoke(null, obj.toString());
             } catch (SecurityException e) {
                 e.printStackTrace();
             } catch (NoSuchMethodException e) {
                 e.printStackTrace();
             } catch (IllegalArgumentException e) {
                 e.printStackTrace();
             } catch (IllegalAccessException e) {
                 e.printStackTrace();
             } catch (InvocationTargetException e) {
                 e.printStackTrace();
             }
         }
         //if(type.equals(Enum))
         return null;
     }
     
     public static void main(String[] argc){
         OutputFormat format = OutputFormat.BINARY;
         //OutputFormat.valueOf(name)
         //format.valueOf(name)
         OutputFormat myEnum= (OutputFormat) getValue(format.getClass(),"BINARY");
         System.out.println(format.toString());
     }
 }
2
5
分享到:
评论

相关推荐

    Objective-c对象组装XML

    4 利用解析类解析并展现到UIView 部分代码如下: @implementation XmlPackage @synthesize obj; @synthesize isList; @synthesize xmlString; @synthesize objectName; @synthesize lvUp; @synthesize root; @...

    超级有影响力霸气的Java面试题大全文档

    引用类型和原始类型具有不同的特征和用法,它们包括:大小和速度问题,这种类型以哪种类型的数据结构存储,当引用类型和原始类型用作某个类的实例数据时所指定的缺省值。对象引用实例变量的缺省值为 null,而原始...

    DWR.xml配置文件说明书(含源码)

    然而没有办法将不同的集合类类型分别采用不同的转换方法.因为没有办法完全自动进行转换,我们可以应用dwr.xml文件的special signatures syntax配置部分设置类型的转换处理过程. 2.5 DOM Objects DWR 自动将DOM、DOM4J...

    config4j

    一个XML工具类,一个系统工具类,一个结点对象,一个BUILDER,如此而已,我就不信这个小东西对于经常读取XML配置文件的人来说不能提供方便? 大家有心情试试看,提供源码和DEMO! 目前是1.0版本,本人将不...

    freemarker总结

    JAVA模版引擎Freemarker常用标签(一) 1. if指令 这是一个典型的分支控制指令,该指令的作用完全类似于Java语言中的if,if指令的语法格式如下: &lt;#if condition&gt;... &lt;#elseif condition&gt;... &lt;#elseif condition&gt;......

    MapView的使用

    double deltaLng = java.lang.Math.abs(java.lang.Math.abs(geo2_lng) - java.lang.Math.abs(geo1_lng)); double dist = 2*EarthRad*java.lang.Math.asin(java.lang.Math.sqrt(haversine(deltaLat) + java.lang....

    Programming Excel With Vba And .net.chm

    Get an XML Map from a List or Range Section 15.10. XPath Members Section 15.11. Resources Chapter 16. Charting Section 16.1. Navigate Chart Objects Section 16.2. Create Charts Quickly ...

    python3.6.5参考手册 chm

    The plistlib module: A Property-List Parser ctypes Enhancements Improved SSL Support Deprecations and Removals Build and C API Changes Port-Specific Changes: Windows Port-Specific Changes: Mac OS...

    [Go语言入门(含源码)] The Way to Go (with source code)

    The Way to Go,: A Thorough Introduction to the Go Programming Language 英文书籍,已Cross the wall,从Google获得书中源代码,分享一下。喜欢请购买正版。 目录如下: Contents Preface......................

    The way to go

    go程序设计语言 Contents Preface................................................................................................................................. xix PART 1—WHY LEARN GO—GETTING ...

Global site tag (gtag.js) - Google Analytics