JAXB--@XmlType注解标注xml生成顺序
默认情况下,Jaxb编组出来的xml中的字段顺序是随机的,你可以使用@XmlType的propOrder属性
来指定序列化的顺序。
第一步:定义java类时,使用@XmlType(propOrder = { "id", "name", "age","book"})指定输出顺序。
- package step2;
- import java.util.Set;
- import javax.xml.bind.annotation.XmlElement;
- import javax.xml.bind.annotation.XmlElementWrapper;
- import javax.xml.bind.annotation.XmlRootElement;
- import javax.xml.bind.annotation.XmlType;
- @XmlRootElement
- @XmlType(propOrder = { "id", "name", "age","book"})
- public class Customer {
- String name;
- int age;
- int id;
- Set<Book> book;
- @XmlElement(name="name")
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- @XmlElement(name="age")
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- @XmlElement(name="id")
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- @Override
- public String toString() {
- return "Customer [id=" + id + ",name=" + name + ",age=" + age + ",book=" + book + "]";
- }
- @XmlElementWrapper(name="books")
- @XmlElement(name="book")
- public Set<Book> getBook() {
- return book;
- }
- public void setBook(Set<Book> book) {
- this.book = book;
- }
- }
输出的xml:
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <customer>
- <id>100</id>
- <name>suo</name>
- <age>29</age>
- <books>
- <book>
- <id>1</id>
- <name>哈里波特</name>
- <price>100.0</price>
- </book>
- <book>
- <id>2</id>
- <name>苹果</name>
- <price>50.0</price>
- </book>
- </books>
- </customer>
注:
1.对于@XmlElementWrapper标注的属性,不能出现在@XmlType的propOrder列表中。
2.对于所有@XmlElement标注过的属性,必须出现在@XmlType的propOrder列表中。
posted on 2017-04-22 22:03 ilinux_one 阅读(12412) 评论(0) 编辑 收藏 举报