JAXB create invalid nillable element when generate

2019-08-06 13:17发布

问题:

In my xsd I have element

<xs:element name="MyDateElement" type="MyDateElementType" nillable="true" />

<xs:complexType name="MyDateElementType">
    <xs:simpleContent>
        <xs:extension base="xs:date">
            <xs:attribute name="state" type="xs:string" />
            <xs:attribute name="dateFrom" type="xs:date" />
        </xs:extension>
    </xs:simpleContent>
</xs:complexType>

I am using

<artifactId>cxf-codegen-plugin</artifactId>

to generate java classes from wsdl.

So this plugin generate this java class:

public class ParrentClass
    implements Serializable
{

    @XmlElement(name = "MyDateElement", required = true, nillable = true)
    protected MyDateElementType MyDateElement;

// setter and getter

}

public class MyDateElement
    implements Serializable
{

    @XmlValue
    protected Date value;
    @XmlAttribute(name = "state")
    protected String state;
    @XmlAttribute(name = "dateFrom")
    protected Date dateFrom;

    // setter and getter

    }

I think this is still OK.

so now when I create element with null value and just with attributes

protected MyDateElement getDatumStav(String state) {
    MyDateElement element = new MyDateElement();
    element.setState(state);
    return element;
}

JAXB create invalid xml:

<ns:MyDateElement stav="S"></ns:MyDateElement>

(nillable=true is missing)

So can anyone helps me how should I solve this problem.

PS: I know that when in xsd I allow minOccurs=0 then plugin generate java class which contains JAXBElement<MyDateElement> where I can manually set nillable. But I want to avoid this solution because this element is required

PS: Probably there is bug in generating java class from XSD because I found this old bug: https://java.net/jira/si/jira.issueviews:issue-html/JAXB-840/JAXB-840.html . But this should be fixed so I am still confused

回答1:

You can add it in java class with JDOM2 :

For exemple :

Namespace ns0 = Namespace.getNamespace("ns0", "http://...");
Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
SAXBuilder jdomBuilder = new SAXBuilder();
InputStream stream = new ByteArrayInputStream(xmlFileString.getBytes("UTF-8"));
Document jdomDocument = jdomBuilder.build(stream);

Element root = jdomDocument.getRootElement();
Element agreement = root.getChild("Agreement", ns0);

Element co = agreement.getChild("CoOwner", ns0);
if (co.getText().equals(""))
{
    co.setAttribute("nil", "true", xsi);
}

// Return to string
return new XMLOutputter().outputString(jdomDocument);

Output :

<ns0:CoOwner xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true" />