如果不加標註, 類中的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)