@XmlElement且无用的“必需”参数
我把@XmlElement(name = “title”,required = true)放在javabean属性int some_property之前,并且没有为some_property赋值。由于某种原因,生成的 XML 中不会出现此属性。因此,请解释一下必需的含义
代码的一些有意义的部分:
@XmlRootElement(name = "book")
@XmlType(propOrder = { "author", "name", "publisher", "isbn" })
public class Book {
private String name;
private String author;
private String publisher;
private String isbn;
// If you like the variable name, e.g. "name", you can easily change this
// name for your XML-Output:
@XmlElement(name = "title",required = true)
public String getName() {
return name;
}
....
在主线的某个地方:
// create books
Book book1 = new Book();
book1.setIsbn("978-0060554736");
book1.setAuthor("Neil Strauss");
book1.setPublisher("Harpercollins");
bookList.add(book1);
Book book2 = new Book();
book2.setIsbn("978-3832180577");
book2.setName("Feuchtgebiete");
book2.setAuthor("Charlotte Roche");
book2.setPublisher("Dumont Buchverlag");
bookList.add(book2);
JAXBContext context = JAXBContext.newInstance(Bookstore.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
// Write to System.out
m.marshal(bookstore, System.out);
// Write to File
m.marshal(bookstore, new File(BOOKSTORE_XML));
// get variables from our xml file, created before
System.out.println();
System.out.println("Output from our XML File: ");
Unmarshaller um = context.createUnmarshaller();
Bookstore bookstore2 = (Bookstore) um.unmarshal(new FileReader(BOOKSTORE_XML));
ArrayList<Book> list = bookstore2.getBooksList();