1
votes

I have a JAXB generated class PersonType with the properties name, phone, address. In the XSD I define that "phone" minoccurs="1". How can I test programatically(i.e. via reflection, etc), in Java code, if the property "phone" is required or not in the XSD?

Later edit: The JAXB generator creates a class without any "required", etc. attributes. So there's no annotation on the class or it's fields to indicate if it's required or not. However, there's the @XmlElement annotation on the field specifying the XSD equivalent element. So I guess the only solution is to inspect this annotation and then make an XPath or something against the XSD?

Thank you!

1
You want to test that the class contains @XmlElement(required=true) or you want to test that an instance of the class has the require name element?bdoughan
@BlaiseDoughan I need a way to test if that field is required or not in the XSD-side. In the Java generated class, there's no indication of that. Thank you!Dan L.

1 Answers

1
votes

The @XmlElement annotation has a required property (false by default) that is used to indicate that an XML element is required (minOccurs > 0). You could use the java.lang.reflect APIs to get this value from the class.

XML Schema

In the XML schema below the foo element is required and the bar element is not.

<?xml version="1.0" encoding="UTF-8"?>
<schema 
    xmlns="http://www.w3.org/2001/XMLSchema" 
    targetNamespace="http://www.example.org/schema" 
    xmlns:tns="http://www.example.org/schema" 
    elementFormDefault="qualified">

    <complexType name="root">
        <sequence>
            <element name="foo" type="string"/>
            <element name="bar" type="string" minOccurs="0"/>
        </sequence>
    </complexType>

</schema>

Generated Class

Below is the class that was generated from the XML schema. We see that the foo field is annotated with @XmlElement(required=true) anf the bar field is not.

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "root", propOrder = {
    "foo",
    "bar"
})
public class Root {

    @XmlElement(required = true)
    protected String foo;

    protected String bar;

}