尽管目前已有很多将POJO序列化的方式,但鉴于将要被序列化的都是Java的简单对象,对生成的XML也不要求验证,完全可以用下面的代码递归生成:
/**
* <p>get XML document from an object ,author by Jarez Wu
* @param o an object
* @return the XML-encoded String;
*/
public static String getXMLDescription(Object o){
String xmlstr="";
if(o instanceof Number||o instanceof String){//do when is leaf of xml tree,here are some translations for javascript gramma
String str=o.toString();
str=str.replaceAll("/"","/"");
str=str.replaceAll("/n","");
str=str.replaceAll("'","'");
String ret="<![CDATA["+str+"]]>";
return ret;
}
BeanInfo bi=null;
PropertyDescriptor[] props=null;
try {
bi = Introspector.getBeanInfo(o.getClass(),Object.class);
props = bi.getPropertyDescriptors();
for(int i=0;i<props.length;i++){
String propname=props[i].getDisplayName();
try{
Object propvalue=props[i].getReadMethod().invoke(o,null);
if(propvalue.getClass().isArray()){//递归遍历数组
try{
Object[] arr=(Object[])propvalue;
for(int j=0;j<arr.length;j++){
xmlstr+="<"+propname+">";
xmlstr+=getXMLDescription(arr[j]);
xmlstr+="</"+propname+">";
}
}catch(Exception e){
}
}else if(propvalue instanceof AbstractCollection){//递归遍历迭代
Iterator iter=((AbstractCollection)propvalue).iterator();
while(iter.hasNext()){
xmlstr+="<"+propname+">";
xmlstr+=getXMLDescription(iter.next());
xmlstr+="</"+propname+">";
}
}else{
xmlstr+="<"+propname+">";
xmlstr+=getXMLDescription(propvalue);
xmlstr+="</"+propname+">";
}
}catch(Exception e){}
}
}catch(Exception e){
e.printStackTrace();
}
return xmlstr;
}
这段代码生成的XML如下所示: