java Bean 转 XML 格式

(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>

参考:https://www.cnblogs.com/liuk/p/5829389.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值