`

xml在web项目中作为传入传出参数

xml 
阅读更多
/**
*
*/
package util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import bean.Area;

/*****************************************************
*
*@auther liqian
*@since 2013-3-19
****************************************************/
/**
* @author Administrator
*
*/
public class MyApplicationContextUtil  {

/***
* 写入xml返回String
* @param <T>类
* @param obj 类对象
* @param areaList要写入xml的类的集合
* @param Encode xml的 编码
* @param XMLPathAndName  写入的路径
* @return  xml的字符串
*/


public static <T> String writeXmlDocument(T obj, List<T> areaList, String Encode,  
          String XMLPathAndName){
long lasting = System.currentTimeMillis();//效率检测  
Document document = DocumentHelper.createDocument();  
 
        try {  
            XMLWriter writer = null;// 声明写XML的对象   
            OutputFormat format = OutputFormat.createPrettyPrint();  
            format.setEncoding(Encode);// 设置XML文件的编码格式  
 
            //String filePath = XMLPathAndName;//获得文件地址  
//             File file = new File(filePath);//获得文件   
//             if (file.exists()) {  
//                 file.delete();  
//  
//             }  
            // 新建student.xml文件并新增内容  
            String rootname = obj.getClass().getSimpleName();//获得类名  
            Element root = document.addElement(rootname + "s");//添加根节点  
            Field[] properties = obj.getClass().getDeclaredFields();//获得实体类的所有属性  
           
            for (Object t : areaList) {                                //递归实体  
                Element secondRoot = root.addElement(rootname);            //二级节点  
               
                for (int i = 0; i < properties.length; i++) {                     
                    //反射get方法      
                    Method meth = t.getClass().getMethod(                     
                            "get" 
                                    + properties[i].getName().substring(0, 1)  
                                            .toUpperCase()  
                                    + properties[i].getName().substring(1));  
                    //为二级节点添加属性,属性值为对应属性的值  
                    secondRoot.addElement(properties[i].getName()).setText(  
                            meth.invoke(t).toString());  
 
                }  
            }  
            //生成XML文件  
//             writer = new XMLWriter(new FileWriter(file), format);  
//             writer.write(document);  
//             writer.close();  
            long lasting2 = System.currentTimeMillis();  
            System.out.println("写入XML文件结束,用时"+(lasting2 - lasting)+"ms");  
        } catch (Exception e) { 
        e.printStackTrace();
            System.out.println("XML文件写入失败");  
        }  
        String result = document.asXML();
        System.out.println(result);
return result;
}
public static <T> List<T> readXML(String XML, T t){
List<T> list=new ArrayList<T>();
  long lasting = System.currentTimeMillis();//效率检测  
        try {
//             File f = new File(XML);//读取文件  
            SAXReader reader = new SAXReader();  
           
           
        //    document = reader.read(new ByteArrayInputStream(transMessage
//                  .getBytes("GBK")));            
           
           
            Document doc = reader.read(new ByteArrayInputStream(XML.getBytes("UTF-8")));//dom4j读取  
            Element root = doc.getRootElement();//获得根节点  
            Element foo;//二级节点  
            Field[] properties = t.getClass().getDeclaredFields();//获得实例的属性  
            //实例的get方法  
            Method getmeth;  
            //实例的set方法  
            Method setmeth;  
              
            for (Iterator i = root.elementIterator(t.getClass().getSimpleName()); i.hasNext();) {//遍历t.getClass().getSimpleName()节点  
                foo = (Element) i.next();//下一个二级节点  
                  
               t=(T) t.getClass().newInstance();//获得对象的新的实例  
 
               for (int j = 0; j < properties.length; j++) {//遍历所有孙子节点  
                       System.out.println(properties[j].getType().toString());
 
                    //实例的set方法  
                      setmeth = t.getClass().getMethod(  
                            "set" 
                                    + properties[j].getName().substring(0, 1)  
                                            .toUpperCase()  
                                    + properties[j].getName().substring(1),properties[j].getType());  
                  //properties[j].getType()为set方法入口参数的参数类型(Class类型) 
//                       System.out.println("set fangfa "+setmeth);
//                       System.out.println("获取的值==="+foo.elementText(properties[j].getName()).toString());
                     
                  if(properties[j].getType().toString().equals("int")){
                  setmeth.invoke(t,Integer.parseInt(foo.elementText(properties[j].getName())));//将对应节点的值存入  
                  }
                   if(properties[j].getType().toString().equals("class java.lang.String")){  
                   setmeth.invoke(t,(foo.elementText(properties[j].getName())));//将对应节点的值存入  
                   }
                }  
                list.add(t);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        long lasting2 = System.currentTimeMillis();  
 
        System.out.println("读取XML文件结束,用时"+(lasting2 - lasting)+"ms");  
return list;

}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics