我们有这个JAXB注释:需要JAXB =真正似乎并不需要
@XmlElement(name = "Strategy", required = true)
protected List<Strategy> strategy;
如果没有Strategy
元素存在,不会引发任何异常..这是为什么?我们不应该得到例外吗?
我们有这个JAXB注释:需要JAXB =真正似乎并不需要
@XmlElement(name = "Strategy", required = true)
protected List<Strategy> strategy;
如果没有Strategy
元素存在,不会引发任何异常..这是为什么?我们不应该得到例外吗?
JAXB参考实现不使用此属性进行验证,它纯粹出于文档目的。
如果您需要验证文档,您需要定义一个XML Schema,并使用SchemaFactory
将它注入Marshaller
或Unmarshaller
。
此外,您可以使用beforeMarshal
和afterUnmarshal
方法作为Marshaller和Unmarshaller只具备验证输入。
访问这些方法的方案也允许您为方法声明添加任意的throws
子句。这意味着在实施这些方法时,您可以安全地使用javax.xml.bind.MarshalException
和javax.xml.bind.UnmarshalException
(或您想要的任何类型的Exception
)来发出验证错误的信号。
请参阅[this](http://stackoverflow.com/a/2696765/12604)以获取从'JAXBContext'中加载'Schema'以在Marshaller/Unmarshaller中使用的示例。 – 2013-01-25 16:19:52
我不会说它纯粹是为了文档 - 它也用于模式生成。当您从Java类生成XSD并且具有'required = true'时,XSD中的元素声明将使用'minOccurs =“1”'生成。然后您可以使用XSD来验证XML。 – Jesper 2017-09-30 13:18:07