forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaWriteXmlJaxbEx.java
More file actions
49 lines (38 loc) · 1.48 KB
/
JavaWriteXmlJaxbEx.java
File metadata and controls
49 lines (38 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.zetcode;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.File;
import java.util.ArrayList;
public class JavaWriteXmlJaxbEx {
private static final String BOOKSTORE_XML = "src/main/resources/bookstore.xml";
public static void main(String[] args) throws JAXBException {
var bookList = new ArrayList<Book>();
// create books
var book1 = new Book();
book1.setIsbn("978-0060554736");
book1.setName("The Game");
book1.setAuthor("Neil Strauss");
book1.setPublisher("Harpercollins");
bookList.add(book1);
var book2 = new Book();
book2.setIsbn("978-3832180577");
book2.setName("Feuchtgebiete");
book2.setAuthor("Charlotte Roche");
book2.setPublisher("Dumont Buchverlag");
bookList.add(book2);
// create bookstore, assign books
var bookstore = new BookStore();
bookstore.setName("Fraport Bookstore");
bookstore.setLocation("Livres belles");
bookstore.setBookList(bookList);
// create JAXB context and instantiate marshaller
var context = JAXBContext.newInstance(BookStore.class);
var 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));
}
}