MOXy忽略XmlElement(required = true)

时间:2014-02-06 03:21:56

标签: xml unmarshalling moxy

我有以下POJO:

@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;
    ...
}

当响应XML TSSEVENTID 标记丢失时,我得到一个DataList,其中Event.id字段为NULL,无论set required = true。什么都没有失败。 这是预期的行为吗?如何启用验证?

Unmarshall代码:

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

相关性:

<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.moxy</artifactId>
    <version>2.5.1</version>
</dependency>

1 个答案:

答案 0 :(得分:1)

如果缺少必需元素,则JAXB (JSR-222)实现不会抛出异常或ValidationEventrequired上的@XmlElement标志仅影响XML模式的生成方式。

<强>演示

在下面的演示代码中,我在ValidationEventHandler上指定了Unmarshaller以捕获任何异常。使用MOXy或JAXB参考实现运行此代码不会导致抛出任何异常。

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中/输出

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

启用验证

  

如何启用验证?

您可以在Schema上设置Unmarshaller的实例,以验证输入。