Jaxb:验证子元素



如何验证Jaxb中的子元素?我使用了以下代码:

JAXBContext jaxbContext = JAXBContext.newInstance(TCreateRecord.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(XSD_URL);
marshaller.setSchema(schema);
marshaller.marshal(createRecord, new DefaultHandler());

首先我得到了

[com.sun.istack.SAXException2: unable to marshal type "ru.egisso.types.package_reg._1_0.TPackage$Elements$CreateRecord" as an element because it is missing an @XmlRootElement annotation]

但在更改代码并使用JAXBElement后,如下所示:

JAXBContext jaxbContext = JAXBContext.newInstance(TCreateRecord.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(XSD_URL);
marshaller.setSchema(schema);
QName _Package_QNAME = new QName("urn://egisso-ru/types/package-REG/1.0.1", "createRecord");
JAXBElement<TCreateRecord> jaxbElement=new JAXBElement<TCreateRecord>(_Package_QNAME,TCreateRecord.class,null,createRecord);
marshaller.marshal(jaxbElement, new DefaultHandler());

我得到了另一个:

[com.sun.istack.SAXException2: Instance of "ru.egisso.types.package_reg._1_0.TPackage$Elements$CreateRecord" is substituting "ru.egisso.types.package_reg._1_0.TCreateRecord", but "ru.egisso.types.package_reg._1_0.TPackage$Elements$CreateRecord" is bound to an anonymous type.]

我终于想出了一个解决方案,它没有解决问题中描述的问题,但它满足了我的需求。我已经为编组器设置了一个监听器,在其中我可以计算已经编组的特定类型的元素。

marshaller.setListener(new Marshaller.Listener() {
int i = 0;
@Override
public void afterMarshal(Object source) {
if (source instanceof TCreateRecord) {
appendToLogAndView("Record " + (++i) + " of " + createRecords + " is written");
}
super.afterMarshal(source);
}
});

相关内容

  • 没有找到相关文章

最新更新