package com.support.ajax;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.AbstractCollection;
import java.util.Iterator;
public class AjaxUtil {
/**
* <p>get XML document from an object ,author by Jarez Wu
* @param o an object
* @return the XML-encoded String;
*/
public static String toXml(Object o){
String xmlstr="";
if(o.getClass().isArray()){
Object[] arr=(Object[])o;
for(int i=0;i<arr.length;i++){
xmlstr+=getXMLDescription(arr[i]);
}
}else if(o instanceof AbstractCollection){
Iterator iter=((AbstractCollection)o).iterator();
while(iter.hasNext()){
xmlstr+=getXMLDescription(iter.next());
}
}else{
xmlstr+=getXMLDescription(o);
}
return xmlstr;
}
/**
* <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||o instanceof Boolean){//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;
}
}