(1)先定义一个Bean 转 XML 的工具类
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class BeanToXmlUtil {
public static String beanToXml(Object obj, Class<?> cls) throws JAXBException {
return beanToXml(obj, cls, false);
}
public static String beanToXml(Object obj, Class<?> cls, boolean format) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(cls);
Marshaller marshaller = context.createMarshaller();
//去掉生成 xml 的默认报文头
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
//输出格式化
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, format);
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
return writer.toString();
}
}
(2)示例:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="Student")
public class StudentVo{
private String id;
private String code;
private String name;
@XmlElement(name = "ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlElement(name = "Code")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@XmlElement(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="List")
public class StudentListVo {
List<StudentVo> studentVoList;
public List<StudentVo> getOrderGoodsList() {
return studentVoList;
}
public void setOrderGoodsList(List<StudentVo> studentVoList) {
this.studentVoList= studentVoList;
}
}
(4)使用
StudentVo studentVo1 = new StudentVo ();
studentVo1.setId("1");
studentVo1.setCode("A001");
studentVo1.setName("张三");
StudentVo studentVo2 = new StudentVo ();
studentVo2.setId("2");
studentVo2.setCode("A002");
studentVo2.setName("李四");
List<StudentVo> studentList = new ArrayList<OrderGoodsVo>();
studentList.add(studentVo1);
studentList.add(studentVo2);
StudentListVo list = new StudentListVo();
list.setOrderGoodsList(studentList);
String xmlList = BeanToXmlUtil.beanToXml(list, StudentListVo.class, true);
System.out.println(xmlList);
<List>
<Student>
<ID>1</ID>
<Code>A001</Code>
<Name>张三</Name>
</Student>
<Student>
<ID>2</ID>
<Code>A002</Code>
<Name>李四</Name>
</Student>
</List>