@XmlRootElement对应了xml文件中的一个Element
如果不加标注, 类中的field都会变成子Element
如
在标注的时候, 要求哪些Field是基本类型,否则必须指明, 如下
当你对Field进行指定的时候, 最好在getter函数处指定,否则会出现Class has two properties of the same name的错误。
据说是因为getter跟field, 一个对应public, 一个对应private的缘故造成的
因为加了@XmlElementWrapper, 所以生成如下的结果
除此之外, 在指定marshaller的时候要注意一下问题
上面的m.marshal的第一个参数是对应的BookStore类的实例,不要不小心写成m自身
即m.marshal(m, System.out)
如果不加标注, 类中的field都会变成子Element
如
@XmlRootElement(name = "book") @XmlType(propOrder = { "author", "name", "publisher", "isbn" }) public class Book { private String name; private String author; private String publisher; private String isbn; //ignore setter and getter here }; 最后会变成 <book> <author>Neil Strauss</author> <name>The Game</name> <publisher>Harpercollins</publisher> <isbn>978-0060554736</isbn> </book> |
@XmlRootElement(namespace = "de.vogella.xml.jaxb.model") public class Bookstore { private ArrayList<Book> bookList; private String name; private String location; public void setBookList(ArrayList<Book> bookList) { this.bookList = bookList; } @XmlElementWrapper(name = "bookList") //在book的列表外生成一个包装函数 @XmlElement(name = "book")//Book不是基本类型,所以这里必须指定 public ArrayList<Book> getBooksList() { return bookList; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } } |
当你对Field进行指定的时候, 最好在getter函数处指定,否则会出现Class has two properties of the same name的错误。
据说是因为getter跟field, 一个对应public, 一个对应private的缘故造成的
因为加了@XmlElementWrapper, 所以生成如下的结果
<bookList> //bookList就是XmlElementWrapper的作用 <book> <author>Neil Strauss</author> <name>The Game</name> <publisher>Harpercollins</publisher> <isbn>978-0060554736</isbn> </book> <book> <author>Charlotte Roche</author> <name>Feuchtgebiete</name> <publisher>Dumont Buchverlag</publisher> <isbn>978-3832180577</isbn> </book> </bookList> |
除此之外, 在指定marshaller的时候要注意一下问题
JAXBContext context = JAXBContext.newInstance(BookStore.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m.marshal(bookstore, System.out); |
上面的m.marshal的第一个参数是对应的BookStore类的实例,不要不小心写成m自身
即m.marshal(m, System.out)