Приведенный ниже код правильно работает для демаршалирования XML из потока по одному объекту за раз.
Но когда я раскомментирую строку unmarshaller.setSchema(schema)
, программа выдает исключение:
[org.xml.sax.SAXParseException: cvc-elt.1: не удается найти объявление элемента «Подписчик».]
Я уже проверил XML с помощью класса javax.xml.validation.Validator
, но моя цель — одновременно проверять и демаршалировать, по одному элементу за раз.
Это мой текущий код:
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File("/Path to xsd"));
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new FileReader("/Path to xml"));
JAXBContext jaxbContext = JAXBContext.newInstance(SubscriberType.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
//unmarshaller.setSchema(schema);
streamReader.nextTag();
streamReader.require(XMLStreamConstants.START_ELEMENT, null, "Subscribers");
streamReader.nextTag();
while (streamReader.getEventType() == XMLStreamConstants.START_ELEMENT) {
JAXBElement<SubscriberType> pt = unmarshaller.unmarshal(streamReader, SubscriberType.class);
//do something with the unmarshalled object pt...store to db ect.
if (streamReader.getEventType() == XMLStreamConstants.CHARACTERS) {
streamReader.next();
}
}
Выдержка из моей схемы subscriber.xsd:
<?xml version="1.0" encoding="UTF-8" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
elementFormDefault="unqualified"
attributeFormDefault="unqualified">
<xsd:element name="Subscribers" type="SubscriberType" />
<xsd:complexType name="SubscriberType">
<xsd:sequence>
<xsd:element name="Subscriber"
type="SubscriberInformation"
minOccurs="1"
maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>