Question

I have the following POJOs:

@XmlRootElement(name = "Root")
@XmlAccessorType(XmlAccessType.FIELD)
public class DataList<T>
{
    @XmlElementWrapper(name="ResultTableSection")
    @XmlAnyElement(lax = true)
    public List<T> elements;
}

@XmlRootElement(name = "ResultTable")
@XmlAccessorType(XmlAccessType.FIELD)
public class Event
{
    @XmlElement(name = "TSSEVENTID", required = true)
    public Integer id;
    ...
}

When in the response XML TSSEVENTID tag is missing I get a DataList in which Event.id field is NULL regardless of the set required=true. Nothing fails. Is it the expected behavior ? How can I enable validation ?

Unmarshall code:

JAXBContext.newInstance(DataList.class, Hall.class).createUnmarshaller().unmarshal(xmlDocument);

Dependency:

<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.moxy</artifactId>
    <version>2.5.1</version>
</dependency>
Was it helpful?

Solution

A JAXB (JSR-222) implementation is not expected to throw an exception or ValidationEvent if a required element is missing. The required flag on @XmlElement only impacts how an XML Schema is generated.

Demo

In the demo code below I have specified a ValidationEventHandler on the Unmarshaller to catch any exceptions. Running this code with either MOXy or the JAXB reference implementation won't result in any exceptions being thrown.

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(DataList.class, Event.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();

        unmarshaller.setEventHandler(new ValidationEventHandler() {
            @Override
            public boolean handleEvent(ValidationEvent event) {
                System.out.println(event.getMessage());
                return false;
            }
        });

        File xml = new File("src/forum21593351/input.xml");
        DataList dl = (DataList) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(dl, System.out);

    }

}

input.xml/Output

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <ResultTableSection>
        <ResultTable>
        </ResultTable>
    </ResultTableSection>
</Root>

Enabling Validation

How can I enable validation ?

You can set an instance of Schema on your Unmarshaller to have the input validated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top