javabean字段如何生成特殊形式的xml 值
2018-06-20 · 国内最优秀java资源共享平台
关注
展开全部
//1.需要 用dom4j jar包 (maven依赖
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.0</version>
</dependency>)
//2.输出javabean的xml格式字符串
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
public class JavaBeanXml {
private String id;
private String name;
private Integer age;
public JavaBeanXml(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();
}
}
//3.测试类
public class JavaBeanXmlTest {
public static void main(String[] args) {
JavaBeanXml jxml=new JavaBeanXml("1","张三",23);
System.out.println(jxml.getXMLString());
}
}
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.0</version>
</dependency>)
//2.输出javabean的xml格式字符串
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
public class JavaBeanXml {
private String id;
private String name;
private Integer age;
public JavaBeanXml(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();
}
}
//3.测试类
public class JavaBeanXmlTest {
public static void main(String[] args) {
JavaBeanXml jxml=new JavaBeanXml("1","张三",23);
System.out.println(jxml.getXMLString());
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询