How to implement @XmlElement.required
flag using @XmlPath
annotation in EclipseLink MOXy 2.4.1 version?
1 Answers
You can use the @XmlElement(required=true)
along with the @XmlPath
annotation to specify that the leaf element is required.
Customer
Below is a sample domain model with two fields mapped with @XmlPath
on one of them I've also used @XmlElement(required=true)
.
package forum13854920;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
@XmlPath("personal-info/first-name/text()")
private String firstName;
@XmlPath("personal-info/last-name/text()")
@XmlElement(required=true)
private String lastName;
}
jaxb.properties
To use MOXy as your JAXB provider you need to include a file called jaxb.properties
in the same package as your domain model with the following entry:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
XML Schema
Below is the XML schema that corresponds to the domain model. Note how the last-name
element does not have minOccurs="0"
.
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:complexType name="customer">
<xsd:sequence>
<xsd:element name="personal-info" minOccurs="0">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="first-name" type="xsd:string" minOccurs="0"/>
<xsd:element name="last-name" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
Demo
The following demo code can be used to generate the XML schema.
package forum13854920;
import java.io.IOException;
import javax.xml.bind.*;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class);
jc.generateSchema(new SchemaOutputResolver() {
@Override
public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException {
StreamResult result = new StreamResult(System.out);
result.setSystemId(suggestedFileName);
return result;
}
});
}
}
Currently EclipseLink JAXB (MOXy) does not have the equivalent of the required
property on the @XmlElement
annotation for the other segments of the path. If you are interested in this behaviour please enter an enhancement request using the link below: