【发布时间】:2011-08-17 16:56:43
【问题描述】:
下面的代码可以正确地从流中一次解组一个对象的 XML。
但是当我取消注释 unmarshaller.setSchema(schema) 行时,程序会抛出异常:
[org.xml.sax.SAXParseException: cvc-elt.1: 找不到元素“订阅者”的声明。]
我已经使用 javax.xml.validation.Validator 类验证了 XML,但我的目标是同时验证和解组,一次一个元素。
这是我当前的代码:
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>
【问题讨论】:
-
您能给我们看看架构文件吗?您基本上只验证 XML 的提取,而不是整个文档。您是否使用验证器验证了整个文档?如果架构中唯一的元素声明是针对根节点的,那么他找不到“订阅者”的声明是有道理的。
-
你说的很有道理...我会编辑架构并试一试。