While going through the XML marshaling and unmarshaling techniques in JAVA
, I came across this doubt,Why we do we have JAXB
related packages in other apis like jakarta-xml-bind-api
and jaxb-api
, when we already have it in the jdk
?
//This method convert object to Xml
public void testObjectToXml() throws JAXBException, FileNotFoundException {
JAXBContext jaxbContext = JAXBContext.newInstance(Product.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(product, new File("product.xml"));
marshaller.marshal(product, System.out);
}
//This method convert xml to object
private static Bookstore convertXMLToObject() {
try {
JAXBContext context = JAXBContext.newInstance(Bookstore.class);
Unmarshaller un = context.createUnmarshaller();
Bookstore bookstore = (Bookstore) un.unmarshal(new File(BOOKSTORE_XML));
List < Book > list = bookstore.getBooksList();
for (Book book: list) {
System.out.println("Book: " + book.getName() + " from " + book.getAuthor());
}
} catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.