您好,欢迎访问一九零五行业门户网

java对象转换为xml格式的示例代码分享

java对象转换为xml格式的示例代码分享
package com.io; public class person { private string name; private integer age; private string hobby; public string getname() { return name; } public void setname(string name) { this.name = name; } public integer getage() { return age; } public void setage(integer age) { this.age = age; } public string gethobby() { return hobby; } public void sethobby(string hobby) { this.hobby = hobby; } public person(string name, integer age, string hobby) { super(); this.name = name; this.age = age; this.hobby = hobby; } public person() { super(); } } package com.io; import java.io.file; import java.io.filewriter; import java.io.ioexception; import java.io.writer; import java.lang.reflect.field; import java.lang.reflect.invocationtargetexception; import java.lang.reflect.method; import org.dom4j.documenthelper; import org.dom4j.element; import org.dom4j.io.xmlwriter; public class xmlutil { /** * 使用dom4j将对象生成xml文件 * @param object 任意对象 * @return * @throws securityexception * @throws nosuchmethodexception * @throws invocationtargetexception * @throws illegalaccessexception * @throws illegalargumentexception * @throws ioexception */ public static string objectsingledom4jtoxml(object object,string path) throws securityexception, nosuchmethodexception, illegalargumentexception, illegalaccessexception, invocationtargetexception, ioexception{ org.dom4j.document document = documenthelper.createdocument(); element root = document.addelement(object.getclass().getsimplename()+"s"); element child = root.addelement(object.getclass().getsimplename()); field[] fields = object.getclass().getdeclaredfields(); for (field field : fields) { method method = object.getclass().getmethod("get"+field.getname().substring(0,1).touppercase()+field.getname().substring(1,field.getname().length())); child.addelement(field.getname()).settext(method.invoke(object)+""); } file dir = new file(path); string prefix = ".xml"; if(!dir.isdirectory()) dir.mkdirs(); file file = new file(dir+"\\"+object.getclass().getsimplename()+prefix); if(!file.exists())file.createnewfile(); file.canexecute(); file.canread(); file.canwrite(); writer filewriter = new filewriter(file); xmlwriter xmlwriter = new xmlwriter(filewriter); xmlwriter.write(document); xmlwriter.close(); return document.asxml(); } public static void main(string[] args) throws securityexception, nosuchmethodexception, ioexception { person person = new person("test", 24, "看电影、上网"); string str; try { str = objectsingledom4jtoxml(person,"f://create"); system.out.println(str); } catch (illegalargumentexception e) { e.printstacktrace(); } catch (illegalaccessexception e) { e.printstacktrace(); } catch (invocationtargetexception e) { e.printstacktrace(); } } }
以上就是java对象转换为xml格式的示例代码分享的详细内容。
其它类似信息

推荐信息