规定在JAXB中只允许一个元素的一个实例? [英] Stipulate that only one instance of an element is allowed in JAXB?

查看:97
本文介绍了规定在JAXB中只允许一个元素的一个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一些XML传递给RESTful Web服务:

I am passing some XML to a RESTful web service:

<root>
    <element1/>
        <element2/>
    <element3/>
</root>

Web服务将解组此XML,我想确保XML有效。

The web service will unmarshal this XML, and I want to ensure that the XML is valid.

我使用了一个模式来创建Java对象,在这个模式中 element1 有一个 maxOccurs = 1 属性,但这对创建的Java对象没有影响(例如,添加 minOccurs = 1 将导致在required = true中添加到 @XMLElement 注释中。在解组传递Web服务的XML时,如果应该只出现一次的元素多次出现,则将解析该元素的最后一个实例。我不希望这种情况发生,因为我希望能够提醒客户端他们发送的XML无效,并且他们应该删除任何不适用的元素 - 而不是随意接受最后一个元素。我相信这将涉及在解组之前进行一些预先验证 - 我可能能够使用beforeUnmarshal方法。

I used a schema to create the Java objects, and in this schema element1 has a maxOccurs=1 attribute but this has no effect on the Java objects that are created (unlike, for example, adding minOccurs=1 which will result in "required=true" being added to the @XMLElement annotation). When unmarshalling the XML that is passed the web service, if an element that should appear only once appears multiple times, the last instance of the element will be parsed. I do not want this to happen, as I want to be able to alert the client that the XML they sent is not valid and that they should remove whatever element does not apply - not just arbitrarily accept the last element. I believe this will involve a little pre-validation before unmarshalling - and I may be able to make use of the beforeUnmarshal method.

在做了一些研究后,它是我的理解是没有JAXB注释允许我指定 element1 只能存在一次。是这样的吗?是否可以在没有架构的情况下验证这一点?

After doing a bit of research, it is my understanding that there is no JAXB annotation that will allow me to specify that element1 can exist only once. Is this the case? Is it possible to validate this at all without a schema?

推荐答案

我通过在Java对象中允许元素的多个实例解决了这个问题:

I have worked around this issue by allowing multiple instances of the element in the Java object:

@XmlElement(name = "element1", required = true)
private List<element1> element1;

这将允许我在 afterUnmarshal之后检查我的列表大小方法,如果列表的大小大于1,我可以抛出一个新的 ValidationException

This will allow me to check the size of my list in the afterUnmarshal method, and if the size of the list is greater than 1, I can throw a new ValidationException.

这篇关于规定在JAXB中只允许一个元素的一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆