javaxsdjaxbmoxy

How to find if an XSD element is required using MOXy Dynamic JAXB?


I'm trying to get information out of an XSD using MOXy's DynamicJAXBContext. One of the properties I'm trying to get is if an attribute or element is required. From what I understand, if an element has minOccurs="1" it means it is required.

The issue is that I haven't found a way to get this.

Here's the code I have until now:

DynamicJAXBContext jaxbContext = 
                DynamicJAXBContextFactory.createContextFromXSD(is, new MyEntityResolver(), null, null);


        Collection<ClassDescriptor> descriptors = jaxbContext.getXMLContext().getSession().getDescriptors().values();
        for (ClassDescriptor desc : descriptors) {
            if (desc.getJavaClassName() != null) {
                System.out.println("=================================");
                System.out.println("Class: " + desc.getJavaClassName());
                desc.getMappings().forEach(dm ->{
                    System.out.println(dm.getAttributeName());

                    System.out.println(dm.getClass().getName());
                    if(dm instanceof XMLDirectMapping) {
                        XMLDirectMapping xmlInfo = (XMLDirectMapping)dm;
                        System.out.println(xmlInfo);
                    }
                    if(dm.getAttributeClassification() != null) {
                        System.out.println(dm.getAttributeClassification().getName());
                    }
                    if(dm.getReferenceDescriptor() != null) {
                        System.out.println(dm.getReferenceDescriptor().getJavaClassName());
                    }
                 });

            }
        }

Until now, I have been able to get information regarding the attribute type, if it's a collection and the collection type.

I've tried exploring other methods of the dm variable including isOptional() and getField().isNullable() and both return true for attributes where minOccurs="1"


Solution

  • I found out that the object returned by the getField() is actually of type XMLField which is a subclass of the general type returned by that method DatabaseField. The XMLField has an isRequired() method that effectively returns if the attribute is required.

     if(dm.getField() instanceof XMLField) {
         XMLField field = (XMLField)dm.getField();
         System.out.println(field.isRequired());
     }