Dynamic java bean from xsd

守給你的承諾、 提交于 2019-11-29 07:30:05

You could use EclipseLink MOXy's Dynamic JAXB for this use case (I'm the MOXy tech lead).

Create the Dynamic JAXB Context:

The JAXBContext can be bootstrapped from an XML:

FileInputStream xsdInputStream = new FileInputStream("src/example/customer.xsd");
DynamicJAXBContext jaxbContext = 
    DynamicJAXBContextFactory.createContextFromXSD(xsdInputStream, null, null, null);

Unmarshal the XML:

Then you use an unmarshaller to convert the XML into objects:

FileInputStream xmlInputStream = new FileInputStream("src/example/dynamic/customer.xml");
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
DynamicEntity customer = (DynamicEntity) unmarshaller.unmarshal(xmlInputStream);

Interact with the Data:

The instance of DynamicEntity you get back is a generic object with get/set methods that take a property name. The property name corresponds to what would have been generated on the static class by XJC.

DynamicEntity address = jaxbContext.newDynamicEntity("org.example.Address");
address.set("street", "1 Any Street").set("city", "Any Town");
customer.set("address", address);

Marshal the Object:

Then you use a marshaller to convert the XML into objects:

Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(customer, System.out);

For more information see:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!