繁体   English   中英

JAXB 编组和解组

[英]JAXB marshaling and unmarshaling

在通过 JAVA 中的JAVA编组和解组技术时,我遇到了这个疑问,为什么我们在其他 api(如jakarta-xml-bind-apijaxb-api )中有JAXB相关包,而我们已经在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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM