问题
I'm generating java classes from XSD
using cxf-xjc-plugin
and xsdtojava
plugin.
Problem: I have no control of the xsd
, and one element has a xs:choice
which results in a JAXBElement
. Unfortunately my xml serializer jackson
cannot handle JAXBElement
s. So I'm trying to achieve autogeneration to an Object
rather than JAXBElement
. But how?
The xsd I have no control of:
<xs:element name="payment">
<xs:complexType>
<xs:choice maxOccurs="2">
<xs:element name="creditcard">
...
</xs:element>
<xs:element name="debitcard">
...
</xs:element>
<xs:element name="iban">
...
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
xsdtojava generates:
@XmlRootElement
public class AutogeneratedReq {
@XmlElementRefs({
@XmlElementRef(name = "creditcard", type = JAXBElement.class, required = false),
@XmlElementRef(name = "debitcard", type = JAXBElement.class, required = false),
@XmlElementRef(name = "iban", type = JAXBElement.class, required = false)
})
private List<JAXBElement<?>> payment;
}
But my goal is the following:
@XmlElements({
@XmlElement(name="creditcard", type=Creditcad.class, required = false),
@XmlElement(name="debitcard", type=Debitcard.class, required = false),
@XmlElement(name="iban", type=Iban.class, required = false)
})
protected List<Object> payment;
Or as well it would be ok generating each of the choices as single elements:
private List<Ceditcard> creditcard;
private List<Debitcard> debitcard;
private List<Iban> iban;
I tried achieving this by using a binding file:
<?xml version="1.0" encoding="UTF-8"?>
<bindings xmlns="http://java.sun.com/xml/ns/jaxb"
version="2.1">
<globalBindings choiceContentProperty="true"/>
</bindings>
But that did not help. What could I try more?
回答1:
Solution is to use the simplify
jaxb plugin and generating the choice elements with <simplify:as-element-property/>
.
maven:
<dependency>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-basics</artifactId>
</dependency>
xsdtojava maven config with cxf-xjc-plugin
must use:
<xsdOption>
<bindingFile>${project.basedir}/src/main/resources/choice-binding.xml</bindingFile>
<extensionArgs>
<extensionArg>-Xsimplify</extensionArg>
</extensionArgs>
</xsdOption>
choice-binding.xml:
axb:bindings
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
xmlns:simplify="http://jaxb2-commons.dev.java.net/basic/simplify"
jaxb:extensionBindingPrefixes="xjc simplify"
jaxb:version="2.1">
<jaxb:bindings schemaLocation="xsd/booking/bookingRequest.xsd">
<jaxb:bindings multiple="true" node="//xs:element[@name='payment']//xs:complexType//xs:choice//xs:element">
<simplify:as-element-property/>
</jaxb:bindings>
</jaxb:binding>
</jaxb:bindings>
来源:https://stackoverflow.com/questions/47526881/how-to-prevent-autogeneration-of-jaxbelement-for-xschoice-using-xsdtojava