使用jaxb注解的小技巧-给xml结构增加封装

1.使用maven引入jaxb依赖

jdk1.6以上自带了jaxb,但我还是推荐显式指定依赖:

<dependency>
  <groupid>javax.xml.bind</groupid>
  <artifactid>jaxb-api</artifactid>
  <version>2.2.7</version>
</dependency>

2.构造一个封装类

下面的类Wrapper,使用Wrapper.wrapper(yourObject),就能把yourObject的结构封装在<root><yourObject></yourObject></root>标签里。

@XmlRootElement(name = "root")
public class Wrapper {

	public static Wrapper wrapper(Object object) {
		Wrapper wrapper = new Wrapper();
		wrapper.addElement(object);
		return wrapper;
	}

	@XmlAnyElement
	private List<Object> root;

	private Wrapper() {
		root = new ArrayList<Object>();
	}

	public void addElement(Object object) {
		root.add(object);
	}
}

如果需要修改外层的封装标签,修改@XmlRootElement(name = “your_tag”)即可。

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.