xsd转换为java bean,来自xsd的动态java bean

I have two applications, one acting as client and the other as server. In server application I generate ObjectFactory and classes using xjc from Eclipse. As a result, one of this classes is called widgetEvenCall. From the xsd:

...

JAXB xjc generates the classes WidgetEventCall, WidgetEventDescriptor and WidgetParameter, with their getters and setters.

The client application, which don't have neither those classes nor the ObjectFactory, calls remotely a service on server application, getting as result one XML like:

. . .

...

...

...

. . .

Luckily, client application has access to the .xsd definition. My question is: Is possible, having the xml content and the xsd definition, to create the objects for widgetEventCall, widgetEventDescriptor and widgetParameter like if they were created by xjc, including getters and setters, keeping the client application with no knowledge about them, using exclusively reflection? Is there one automated way to reach this?

my goal is to use this result into a JSP file, i.e. putting the object into request and accessing it like widgetEventCall.widgetParameter[0].someProperty, so I need the getters to be generated.

Thanks in advance.

Joan.

解决方案

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:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值