提示
目前只支持基本类型和封装类型
package ztf.question1;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
public class Application {
//存在问题,没有模仿缩进
public static void main(String[] args){
Person person=new Person();
person.setName("ddd");
person.setAge(23);
Address address=new Address("chonqqing","Hong Guang Street");
person.setAddress(address);
System.out.println(ObjectToXml.writeXML(person.getClass(),person));
}
}
package ztf.question1;
public class Address {
private String province;
private String street;
public Address() {
}
public Address(String pro,String street){
this.province=pro;
this.street=street;
}
public String getProvince(){
return this.province;
}
public void setProvince(String province){
this.province=province;
}
public String getStreet(){
return this.street;
}
public void setStreet(String street){
this.street=street;
}
}
package ztf.question1;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ObjectToXml {
public static String writeXML(Class class1,Object obj){
StringBuilder stringBuilder=new StringBuilder();
try{
stringBuilder.append("<"+class1.getName()+">\n");
Field[] fields = class1.getDeclaredFields();
for(Field field:fields) {
field.setAccessible(true);
Class<?> type = field.getType();
if(type.isPrimitive()||type==String.class) {
stringBuilder.append("<"+field.getName()+">");
Method m = (Method) class1.getMethod(
"get" + getMethodName(field.getName()));
stringBuilder.append(m.invoke(obj));
stringBuilder.append("</"+field.getName()+">\n");
}else {
Method m = (Method) class1.getMethod(
"get" + type.getSimpleName());
stringBuilder.append(writeXML(field.getType(),m.invoke(obj)));
}
}
stringBuilder.append("</"+class1.getName()+">\n");
return stringBuilder.toString();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
private static String getMethodName(String name) {
// TODO Auto-generated method stub
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
}
package ztf.question1;
public class Person {
private String name;
private int age;
private Address address;
public Person(){
this.name="";
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name=name;
}
public int getAge(){
return this.age;
}
public void setAge(int age){
this.age=age;
}
public Address getAddress(){
return this.address;
}
public void setAddress(Address address){
this.address=address;
}
}