简体   繁体   English

规定JAXB中仅允许元素的一个实例?

[英]Stipulate that only one instance of an element is allowed in JAXB?

I am passing some XML to a RESTful web service: 我正在将一些XML传递给RESTful Web服务:

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

The web service will unmarshal this XML, and I want to ensure that the XML is valid. Web服务将解组此XML,并且我想确保XML有效。

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). 我使用了一个架构来创建Java对象,并且在该架构中element1具有maxOccurs=1属性,但这对创建的Java对象没有影响(例如,与添加minOccurs=1不同,这将导致"required=true"添加到@XMLElement批注)。 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. 当解组通过Web服务传递的XML时,如果一个仅应出现一次的元素出现了多次,则该元素的最后一个实例将被解析。 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. 我不希望发生这种情况,因为我希望能够提醒客户端,他们发送的XML无效,并且他们应该删除任何不适用的元素-不仅仅是随意接受最后一个元素。 I believe this will involve a little pre-validation before unmarshalling - and I may be able to make use of the beforeUnmarshal method. 我相信这将需要在进行编组之前进行一些预验证-并且我可以使用beforeUnmarshal方法。

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. 经过一些研究之后,据我了解,没有JAXB注释可以让我指定element1只能存在一次。 Is this the case? 是这样吗 Is it possible to validate this at all without a schema? 没有模式就可以完全验证这一点吗?

I have worked around this issue by allowing multiple instances of the element in the Java object: 我通过允许Java对象中的元素的多个实例来解决此问题:

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

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 . 这将允许我在afterUnmarshal方法中检查列表的大小,如果列表的大小大于1,则可以引发新的ValidationException

Which application calling your application as it is bit difficult to do that on Java layer but you can easily do that at your web service layer where in you can define your minOccurance to 1 ad that will serve. 哪个应用程序在Java层上很难调用它,但是您可以在Web服务层上轻松地做到这一点,在其中可以定义要投放的1个广告的minOccurance。

But if you want to do that on Java layer you need to use XML parser and then count the Occurance of particular tag but it would take a lot of time. 但是,如果要在Java层上执行此操作,则需要使用XML解析器,然后计算特定标记的出现次数,但这会花费很多时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM