注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

和申的个人主页

专注于java开发,1985wanggang

 
 
 

日志

 
 

较好的XML自动生成工具类  

2009-12-07 14:52:30|  分类: Java |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

  该自动生成类可以根据配置DTO类中的反射标签来自动生成xml,可以较快的用于开发,可移植性较强

//////////////////////////////////////////////////////XmlBuilder.java  生成工具类

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com..core.Result;


public class XmlBuilder {

 private XmlBuilder() {
 }

 public static String buildXmlAsString(Object obj) {
  StringWriter writer = new StringWriter(65535);
  buildXml(obj, writer);
  return writer.toString();
 }

 public static void buildXml(Object obj, OutputStream out) {
  try {
   buildXml(obj,
     new BufferedWriter(new OutputStreamWriter(out, "GBK")));
  } catch (UnsupportedEncodingException e) {
   throw new RuntimeException(e);
  }
 }

 public static void buildXml(Object obj, Writer out) {
  Document doc = buildXml(obj);
  OutputFormat format = OutputFormat.createPrettyPrint();
  format.setEncoding("GBK");
  XMLWriter writer = new XMLWriter(out, format);
  try {
   writer.write(doc);
  } catch (IOException e) {
   throw new RuntimeException("write xml as string exception", e);
  } finally {
   try {
    writer.close();
   } catch (IOException e) {
    throw new RuntimeException("close xmlwriter exception", e);
   }
  }
 }

 public static Document buildXml(Object obj) {
  DocumentFactory factory = DocumentFactory.getInstance();
  Element root = factory.createElement("QUERYRESULT");
  Document doc = factory.createDocument(root);
  doc.setXMLEncoding("GBK");
  chooseBuildALL(obj, root);
  return doc;
 }

 private static void chooseBuildALL(Object obj, Element e) {
  if (obj instanceof Throwable) {
   build(e, (Throwable) obj);
  } else if (obj instanceof Result<?>) {
   build(e, (Result<?>) obj);
  } else if (obj instanceof List<?>) {
   e.addElement("TOTALCOUNT").setText(
     ((List)obj).size()+"");
   build(e, (List<?>) obj);
  } else {
   build(e, obj);
  }
 }
 private static void chooseBuild(Object obj, Element e) {
  if (obj instanceof Throwable) {
   build(e, (Throwable) obj);
  } else if (obj instanceof Result<?>) {
   build(e, (Result<?>) obj);
  } else if (obj instanceof List<?>) {
   build(e, (List<?>) obj);
  } else {
   build(e, obj);
  }
 }

 private static void build(Element root, Throwable o) {
  Element ex = root.addElement("ERROR");
  ex.addAttribute("type", o.getClass().getName());
  ex.setText(o.getMessage() == null ? "" : o.getMessage());
 }

 private static void build(Element root, Object o) {
  if (o == null) {
   build(root, new NullPointerException("data is null"));
  } else {
   Class<?> clazz = o.getClass();
   addData(root, o, getTagName(clazz), findPropetyMethods(clazz));
  }
 }

 private static void build(Element root, List<?> list) {  
  if (list.size() == 0){   
   return;
  }
  Class<?> clazz = list.get(0).getClass();
  List<MethodTag> methods = findPropetyMethods(clazz);  
  String tagName = getTagName(clazz);
  Element eList = root.addElement(tagName + 'S').addAttribute("size",
    Integer.toString(list.size()));  
  for (Object o : list) {
   addData(eList, o, tagName, methods);
  }
 }

 private static void build(Element root, Result<?> res) {
  root.addElement("TOTALCOUNT").setText(
    Integer.toString(res.getPageInfo() == null ? 0 : res.getPageInfo().getTotalRowCount()));
  build(root, res.getData());
  Map<Object, Object> otherData = res.getOtherData();
  if (otherData != null) {
   for (Object od : otherData.values()) {
    chooseBuild(od, root);
   }
  }

 }

 private static void addAttribute(Element e,Object o){
  List<MethodTag> attributeMethods = findAttributeMethods(o.getClass());
  for(MethodTag m:attributeMethods){
   Object value;
   try {
    value = m.method.invoke(o);
    
   } catch (Exception e1) {
    throw new RuntimeException("build xml exception", e1);
   }
   if(value != null){
    e.addAttribute(m.tag, value +"");
   }
  }
 }
 private static void addData(Element e, Object o, String tagName,
   List<MethodTag> methods) {
  
  Element eResult = e.addElement(tagName);
  addAttribute(eResult,o);
  for (MethodTag mt : methods) {
   try {
    Object v = mt.method.invoke(o);
    if(v != null){
     Class<?> clazz2 =  v.getClass();
     Entity entity = clazz2.getAnnotation(Entity.class);
     if(entity != null){ 
      List<MethodTag> methods2 = findPropetyMethods(clazz2);      
      String tagName2 = getTagName(clazz2);
      addData(eResult,v,tagName2,methods2);
      continue;
     }else if(v instanceof List){
      addData(eResult,(List)v);
      continue;
     }
    }
    Element ep = eResult.addElement(mt.tag);
    if (v != null){
      ep.setText(v.toString());
    }
    
   } catch (Exception e1) {
    throw new RuntimeException("build xml exception", e1);
   }
  }
 }
 
 private static void addData(Element e, List list) {
  if(list.size() == 0) return;
  Class<?> clazz = list.get(0).getClass();
  Entity entity = clazz.getAnnotation(Entity.class);
  if(entity != null){
   String tagName2 = getTagName(clazz);
   List<MethodTag> methods = findPropetyMethods(clazz);
   for(Object obj:list){    
    addData(e,obj,tagName2,methods);   
    
   }
  }
    
 }

 private static String getTagName(Class<?> clazz) {
  Entity entity = clazz.getAnnotation(Entity.class);
  return ("".equals(entity.value()) ? clazz.getSimpleName() : entity
    .value()).toUpperCase();
 }

 private static List<MethodTag> findPropetyMethods(Class<?> clazz) {
  Method[] allMethods = clazz.getMethods();
  List<MethodTag> methods = new ArrayList<MethodTag>(allMethods.length);
  for (Method method : allMethods) {
   Property p = method.getAnnotation(Property.class);
   if (p != null) {
    MethodTag mt = new MethodTag();
    mt.method = method;
    mt.tag = ("".equals(p.value()) ? method.getName().substring(3)
      : p.value()).toUpperCase();
    mt.order = p.order();
    methods.add(mt);
   }
  }
  Collections.sort(methods,new Comparator<MethodTag>(){

   public int compare(MethodTag o1, MethodTag o2) {
    return o1.order - o2.order;
   }
   
  });
  return methods;
 }
 
 private static List<MethodTag> findAttributeMethods(Class<?> clazz) {
  Method[] allMethods = clazz.getMethods();
  List<MethodTag> methods = new ArrayList<MethodTag>(allMethods.length);
  for (Method method : allMethods) {
   Attribute a = method.getAnnotation(Attribute.class);
   if (a != null) {
    MethodTag mt = new MethodTag();
    mt.method = method;
    mt.tag = ("".equals(a.value()) ? method.getName().substring(3)
      : a.value()).toUpperCase();   
    methods.add(mt);
   }
  }
  return methods;
 }

 private static class MethodTag {
  Method method;
  String tag;
  int order;
 }

}
////////////////////////////////////////////////////////Property .java类

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Property {

 /**
  * property tag name, default MethodName(unincluding "get")
  *
  * @return
  */
 String value() default "";
 int order() default 0;

}
//////////////////////////////////////////////////////////////Entity.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Entity {

 /**
  * entity class tag name, default ClassName
  *
  * @return
  */
 String value() default "";

}

///////////////////////////////////////////////////////////Attribute .java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Attribute {
 String value() default "";
}

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

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

DEMO
////////////////////////////////////////////DEMO 生成的属性类

import java.util.List;

import com.emar.gouwuke.comm.Attribute;
import com.emar.gouwuke.comm.Entity;
import com.emar.gouwuke.comm.Property;

@Entity("Cat")
public class CatDTO{
  private String catId;
  private List<KeyWord> keywordList; 
  /**
   * @return the catId
   */
  @Attribute
  public String getCatId() {
   return catId;
  }

  /**
   * @param catId the catId to set
   */
  public void setCatId(String catId) {
   this.catId = catId;
  }

  /**
   * @return the keywordList
   */
  @Property
  public List<KeyWord> getKeywordList() {
   return keywordList;
  }

  /**
   * @param keywordList the keywordList to set
   */
  public void setKeywordList(List<KeyWord> keywordList) {
   this.keywordList = keywordList;
  }
  
  @Entity
  public static class KeyWord{
   private String value;
   private long searchStat;
   /**
    * @return the value
    */
   @Attribute
   public String getValue() {
    return value;
   }
   /**
    * @param value the value to set
    */
   public void setValue(String value) {
    this.value = value;
   }
   /**
    * @return the searchStat
    */
   @Attribute
   public long getSearchStat() {
    return searchStat;
   }
   /**
    * @param searchStat the searchStat to set
    */
   public void setSearchStat(long searchStat) {
    this.searchStat = searchStat;
   }
   
  }
}
////////////////////////////////////////////////Test类

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import com.emar.gouwuke.dto.CatDTO;

/**
 * @author wanggang
 * @version Dec 1, 2009
 */
public class XmlTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  OutputStream out = System.out;
  /*List list = new ArrayList();
  CatDTO cat = new CatDTO();
  cat.setCatId(111);
  
  List kewwordList = new ArrayList();
  CatDTO.KeyWord keyword = new CatDTO.KeyWord();
  keyword.setValue("呵呵呵呵");
  keyword.setSearchStat(20);
  kewwordList.add(keyword);
  keyword = new CatDTO.KeyWord();
  keyword.setValue("呵呵呵呵");
  kewwordList.add(keyword);
  
  cat.setKeywordList(kewwordList);
  
  list.add(cat);
  
  cat = new CatDTO();
  cat.setCatId(111);
  
  kewwordList = new ArrayList();
  keyword = new CatDTO.KeyWord();
  keyword.setValue("呵呵呵呵");
  keyword.setSearchStat(300);
  kewwordList.add(keyword);
  keyword = new CatDTO.KeyWord();
  keyword.setValue("呵呵呵呵");
  keyword.setSearchStat(400);
  kewwordList.add(keyword);
  
  cat.setKeywordList(kewwordList);
  
  list.add(cat);
  XmlBuilder.buildXml(list, out);*/
 }

}

  评论这张
 
阅读(3574)| 评论(2)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2016