5

我对 JAXB 有一个小问题,但不幸的是我找不到答案。

我有一个类 Customer,有 2 个字段namecity,映射是使用注释完成的,并且两个字段都标记为必需且不可空。

@XmlRootElement(name = "customer")
public class Customer {

    enum City {
        PARIS, LONDON, WARSAW
    }

    @XmlElement(name = "name", required = true, nillable = false)
    public String name;
    @XmlElement(name = "city", required = true, nillable = false)
    public City city;

    @Override
    public String toString(){
        return String.format("Name %s, city %s", name, city);
    }
}

但是,当我提交这样的 XML 文件时:

<customer>
    <city>UNKNOWN</city>
</customer>

我将收到一个 Customer 实例,其中两个字段都设置为 null。

不应该有验证异常还是我在映射中遗漏了什么?

要解组我使用:

JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) unmarshaller.unmarshal(in);
4

2 回答 2

6

您需要使用架构进行验证。JAXB 不能自己进行验证。

SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(ClassUtils.getDefaultClassLoader().getResource(schemaPath));
unmarshaller.setSchema(schema);
于 2013-05-08T17:08:52.083 回答
3

您可以在运行时自动生成模式并将其用于验证。这将完成这项工作:

JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
generateAndSetSchema(unmarshaller);
Customer customer = (Customer) unmarshaller.unmarshal(in);

private void generateAndSetSchema(Unmarshaller unmarshaller) {

    // generate schema
    ByteArrayStreamOutputResolver schemaOutput = new ByteArrayStreamOutputResolver();
    jaxbContext.generateSchema(schemaOutput);

    // load schema
    ByteArrayInputStream schemaInputStream = new ByteArrayInputStream(schemaOutput.getSchemaContent());
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(new StreamSource(schemaInputStream));

    // set schema on unmarshaller
    unmarshaller.setSchema(schema);
}

private class ByteArrayStreamOutputResolver extends SchemaOutputResolver {

    private ByteArrayOutputStream schemaOutputStream;

    public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException {

        schemaOutputStream = new ByteArrayOutputStream(INITIAL_SCHEMA_BUFFER_SIZE);
        StreamResult result = new StreamResult(schemaOutputStream);

        // We generate single XSD, so generator will not use systemId property
        // Nevertheless, it validates if it's not null.
        result.setSystemId("");

        return result;
    }

    public byte[] getSchemaContent() {
        return schemaOutputStream.toByteArray();
    }
}
于 2015-10-01T09:58:11.960 回答