Jaxb:验证子元素

Jaxb: Validate child element

如何验证 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);
    }
});