如何根据javabean中的属性生成xml文件
1个回答
2016-11-18
展开全部
用dom4j来搞,其jar包自己网上下载:
Java code
package bean;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
public class A {
private String id;
private String name;
private Integer age;
public A(String id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
//输出javabean的xml格式字符串
public String getXMLString(){
Document d=DocumentHelper.createDocument();
Element root=d.addElement(this.getClass().getSimpleName());
root.addElement("id").addText(getId());
root.addElement("name").addText(getName());
root.addElement("age").addText(String.valueOf(getAge()));
d.setXMLEncoding("utf-8");
return d.asXML();
}
public static void main(String[] args) {
A a=new A("1","张三",23);
System.out.println(a.getXMLString());
}
}
输出结果:
<?xml version="1.0" encoding="utf-8"?>
<A><id>1</id><name>张三</name><age>23</age></A>
Java code
package bean;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
public class A {
private String id;
private String name;
private Integer age;
public A(String id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
//输出javabean的xml格式字符串
public String getXMLString(){
Document d=DocumentHelper.createDocument();
Element root=d.addElement(this.getClass().getSimpleName());
root.addElement("id").addText(getId());
root.addElement("name").addText(getName());
root.addElement("age").addText(String.valueOf(getAge()));
d.setXMLEncoding("utf-8");
return d.asXML();
}
public static void main(String[] args) {
A a=new A("1","张三",23);
System.out.println(a.getXMLString());
}
}
输出结果:
<?xml version="1.0" encoding="utf-8"?>
<A><id>1</id><name>张三</name><age>23</age></A>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询