日期:2014-05-20  浏览次数:20946 次

【求助】使用jaxb如何序列化 List对象啊

List<Book> books =new ArrayList<Book>();
Book book=new Book();
book.setName="书名1";
book.setContent="内容1";

Book book2=new Book();
book2.setName="书名2";
book2.setContent="内容2";
books.add(book);
books.add(book2);



请问使用jaxb 如何实现 list 和xml之间的相互转化??
非常感谢

------解决方案--------------------
book类

private String name;
private String content;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}


生成xml

List<Book> books =new ArrayList<Book>();
Book book=new Book();
book.setName("书名1");
book.setContent("内容1");

Book book2=new Book();
book2.setName("书名2");
book2.setContent("内容2");
books.add(book);
books.add(book2);

JAXBContext context = JAXBContext.newInstance(Book.class);

Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, "GBK");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

String ns = "book";
XMLOutputFactory output = XMLOutputFactory.newInstance();
output.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);


File file = new File("d:/jaxbtest.txt");
OutputStream out = new FileOutputStream(file);
XMLStreamWriter writer = output.createXMLStreamWriter(out,"UTF-8");
writer.writeStartDocument();
writer.setDefaultNamespace(ns);
writer.writeStartElement(ns,"booklist");

int i = 0;

for(Iterator it = books.iterator();it.hasNext();){
QName qname = new QName("book" + String.valueOf(i));
i++;
Book bk = (Book)it.next();
JAXBElement<Book> bookElement = new JAXBElement<Book>(qname,Book.class,bk);
marshaller.marshal(bookElement, writer);
writer.flush();
}
writer.writeEndElement();
writer.writeEndDocument();
writer.flush();


生成结果如下:
<?xml version='1.0' encoding='UTF-8'?>
<booklist xmlns="book">
<book0 xmlns="">
<content>内容1</content>
<name>书名1</name>
</book0>
<book1 xmlns="">
<content>内容2</content>
<name>书名2</name>
</book1>
</booklist>
------解决方案--------------------
Book.java
@XmlType(propOrder={"name","content"})
@XmlRootElement(name="book")
public class Book {
    private String name;
    private String content;

    @XmlElement
    public final String getContent() {
        return content;