JAXB 注解

@XmlRootElement对应了xml文件中的一个Element
如果不加标注, 类中的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>
在标注的时候, 要求哪些Field是基本类型,否则必须指明, 如下
 
@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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值