日期:2014-05-20 浏览次数:20946 次
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);
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;
}
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();
@XmlType(propOrder={"name","content"})
@XmlRootElement(name="book")
public class Book {
private String name;
private String content;
@XmlElement
public final String getContent() {
return content;