随笔 - 7, 文章 - 12, 评论 - 17, 引用 - 0
数据加载中……

bean与xml的相互转换

package com.test;

import java.io.StringBufferInputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

 

public class BeanXml
{
 /*
  * 用于 genenateXml()方法
  * 从对象中得到值,以生成xml
  */
 public String getFieldValue(Object objValue )
 {
  StringBuffer valuebuf = new StringBuffer();
  if(objValue.getClass().isArray())
  {
   String [] valueArr = (String[])objValue;
   for(int j=0;j<valueArr.length;j++)
   {
    valuebuf.append("<value>"+valueArr[j]+"</value>");
   }
  }
  if(objValue instanceof java.util.List)
  {
   List list  = (List)objValue;
   for(int j=0;j<list.size();j++)
   {
    valuebuf.append("<value>"+list.get(j)+"</value>");
   }
  }
  else if (objValue instanceof java.util.Date)
     {     
   java.util.Date valueDate = (java.util.Date)objValue;
   SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
   valuebuf.append("<value>"+ formatter.format(valueDate)+"</value>");
  }
     else if (objValue instanceof String )
     {
      valuebuf.append("<value>"+objValue+"</value>");
     }
     else if(objValue instanceof Integer)
     {
      valuebuf.append("<value>"+objValue+"</value>");
     }
     else if(objValue instanceof Double)
     {
      valuebuf.append("<value>"+objValue+"</value>");
     }
     else if(objValue instanceof Float)
     {
      valuebuf.append("<value>"+objValue+"</value>");
     }
  return valuebuf.toString();
 }
 /*
  * 用于generateBean方法
  * 功能:从xml中取值,给对象赋值
  */
 public Object getFieldValue(Object object,String name,List valuelist)
 {
  Object objValue=null;
  Object objType =null;
  String fieldname ="";
  Class cls = object.getClass();
  Field[] fields = cls.getDeclaredFields();
  try
  {
   for(int i=0;i<fields.length;i++)
   {
    fieldname = fields[i].getName();
    if(name.equals(fieldname))
    {
     objType = PropertyUtils.getProperty(object, name);
     objValue = getValueByType(objType,valuelist);
     return objValue;
    }
   }
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
  return "";
 }
 
 public Object getValueByType(Object objType,List valuelist)
 {
  Object objValue=null;
  try
  {
   if(objType.getClass().isArray())
   {
    String[] arr=null;
    for(int i=0;i<valuelist.size();i++)
    {
     arr=new String[valuelist.size()];
     arr[i]=(String)valuelist.get(i);
    }
    objValue = arr;
   }
   else if (objType instanceof java.util.List)
   {
    objValue = valuelist;
    
   }
   else if (objType instanceof java.util.Date)
      {     
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
    formatter.applyPattern("yyyyMMdd");
    objValue = formatter.parse((String)valuelist.get(0));    
   }
      else if (objType instanceof String )
      {
       objValue = (String)valuelist.get(0);
      }
      else if(objType instanceof Integer)
      {
       objValue = Integer.valueOf((String)valuelist.get(0));
      }
      else if(objType instanceof Double)
      {
       objValue = Double.valueOf((String)valuelist.get(0));
      }
      else if(objType instanceof Float)
      {
       objValue = Float.valueOf((String)valuelist.get(0));
      }
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
  return objValue;
 }
 
 /**
  * 生成xml
  */
 public String generateXML(Object object)
 {
  Class cls = object.getClass();
  Field[] fields = cls.getDeclaredFields();
  String name= "";
  String type ="";
  String value ="";
  StringBuffer buf =new StringBuffer();
  buf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  buf.append("<package>");
  buf.append("<classname>"+cls+"</classname>");
  try
  {
   for(int i=0;i<fields.length;i++)
   {
    name = fields[i].getName();
    Object objValue = PropertyUtils.getProperty(object, name);
    type = PropertyUtils.getPropertyType(object, name).getName();
    value = getFieldValue(objValue);

    buf.append("<"+name+">");
    buf.append("<property>"+type+"</property>");
    buf.append("<values>"+value+"</values>");
    buf.append("</"+name+">");
   }
   buf.append("</package>");
   
  }catch(Exception e)
  {
   e.printStackTrace();
  }
  return buf.toString();
 }
 /*
  * 生成bean
  */
 public Object generateBean(String strXML)
 {  
  String name ="";
  String type ="";
  List elemlist = new ArrayList();
  
  Object objValue;
  String classname ="";
  Object object =null;
  try
  {
   SAXReader reader = new SAXReader();
   StringBufferInputStream is=new StringBufferInputStream(strXML);
   Document document = reader.read(is);

   Element root = document.getRootElement();
   
   Iterator iter = root.elementIterator();
   if(iter.hasNext())
   {
    classname = ((Element)iter.next()).getTextTrim();
    if(classname.indexOf(" ")>0)
     classname = classname.substring(classname.lastIndexOf(" ")+1);
    object =Class.forName(classname).newInstance();
    for( ;iter.hasNext();)
    {
     Element element = (Element) iter.next();
     name = element.getName();
     type = (element.element("property")).getTextTrim();
     elemlist = element.element("values").elements();
     List valuelist = new ArrayList();
     for(int j=0;j<elemlist.size();j++)
     {
      Element subelement = (Element)elemlist.get(j);
      valuelist.add(subelement.getTextTrim());
     }
     objValue = getFieldValue(object,name,valuelist);
     PropertyUtils.setProperty(object, name, objValue);
    }
   }   
  }catch(Exception e)
  {
   e.printStackTrace();
  }
  return object;
 }
 public static void main(String[] args)
 {
  try
  {
   TestBean tb = new TestBean();
   String [] str = {"123","23"};
   String strxml="";
   List list =new ArrayList();
   list.add("list111");
   list.add("list222");
   list.add("list333");
   tb.id =123;
   tb.setId(123);
   tb.setName("abced");
   tb.setDate(new java.util.Date());
   tb.setArrId(str);
   tb.setList(list);
   BeanXml bx = new BeanXml();
   System.out.println("-------xmlvalue:"+bx.generateXML(tb));
   strxml = bx.generateXML(tb);
   TestBean testb=(TestBean)bx.generateBean(strxml);
   //bx.generateBean(strxml);
   System.out.println("-------id:"+testb.getId());
   System.out.println("-------name:"+testb.getName());
   System.out.println("-------date:"+testb.getDate());
   System.out.println("-------arrid"+testb.getArrId()[1]);
   System.out.println("-------list:"+testb.getList().get(2));
  }catch(Exception e)
  {
   e.printStackTrace();
  }
 }
}

posted on 2007-07-07 16:00 刘浪 阅读(1121) 评论(0)  编辑  收藏 所属分类: code


只有注册用户登录后才能发表评论。


网站导航: