java生成xml文件_什么工具能最方便地由java类生成xml文件?

用XStream写个demo给大家看看:

maven依赖:

com.thoughtworks.xstream

xstream

1.3.1

xpp3

xpp3

1.1.4c

三个类:

Student.javapackage com.simpco.xstreamtest;

import com.thoughtworks.xstream.annotations.XStreamAlias;

@XStreamAlias("Student")

public class Student {

private String name;

private String sex;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getSex() {

return sex;

}

public void setSex(String sex) {

this.sex = sex;

}

public Student() {

super();

}

@Override

public String toString() {

return "Student [name=" + name + ", sex=" + sex + "]";

}

}

Root.javapackage com.simpco.xstreamtest;

import java.util.ArrayList;

import java.util.List;

import com.thoughtworks.xstream.annotations.XStreamAlias;

@XStreamAlias("Root")

public class Root {

@XStreamAlias("StudentList")

private List studentList;

public List getStudentList() {

return studentList;

}

public void setStudentList(List studentList) {

this.studentList = studentList;

}

public void addStudent(Student student){

if(studentList==null){

studentList = new ArrayList();

}

studentList.add(student);

}

}

运行 App.javapackage com.simpco.xstreamtest;

import com.thoughtworks.xstream.XStream;

/**

* Hello world!

*

*/

public class App {

public static void main( String[] args ){

XStream xstream = new XStream();

Root root = new Root();

Student student = new Student();

student.setName("张三");

student.setSex("男");

root.addStudent(student);

Student student1 = new Student();

student1.setName("李四");

student1.setSex("女");

root.addStudent(student1);

// xstream.alias("root", Root.class);

// xstream.alias("Student", Student.class);

// Annotations.configureAliases(xstream, Student.class);

xstream.processAnnotations(Root.class);

xstream.processAnnotations(Student.class);//声明使用Student中的注解别名

String xml = xstream.toXML(root);

String top = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";

System.out.println(top+xml);

// Root rootObj = (Root)xstream.fromXML(xml);

// System.out.println(JSON.toJSONString(rootObj));

}

}

预期结果:<?xml version="1.0" encoding="UTF-8"?>

张三

李四

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值