一些代码片段。

执行 jaxb 解码的 java 编码。非常简单,从网上的教程中复制出来的。

JAXBContext jc = JAXBContext.newInstance( "xmlreadtest" );
Unmarshaller u = jc.createUnmarshaller();

// setting up for validation.
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
StreamSource schemaSource =  new StreamSource(ReadXml.class.getResource("level.xsd").getFile());
Schema schema = schemaFactory.newSchema(schemaSource);
u.setSchema(schema);

// parsing the xml
URL url = ReadXml.class.getResource("level.xml");
Source sourceRoot = (Source)u.unmarshal(url);

来自 xml 文件的问题元素。该元素只包含可忽略的空格。它的格式很糟糕,因为它显示了它在文件中的确切位置。
<HashLine _id='FI6'
ppLine='1'
origLine='1'
origFname='level.cpp'>
</HashLine>

描述此元素的 xsd 元素。
<xs:element name="HashLine">
  <xs:complexType>
    <xs:attribute name="origLine" type="xs:NMTOKEN" use="required" />
    <xs:attribute name="origFname" type="xs:string" use="required" />
    <xs:attribute name="_id" type="xs:ID" use="required" />
    <xs:attribute name="ppLine" type="xs:NMTOKEN" use="required" />
  </xs:complexType>
</xs:element>

错误是
[org.xml.sax.SAXParseException: cvc-complex-type.2.1: Element 'HashLine' must have no character or element information item [children], because the type's content type is empty.]

我已经验证错误来自该元素。

它无需验证即可正常加载。但是我需要使用验证,因为我将对应用程序进行大量更改和添加,并且我必须确保所有内容都正确编码/解码。

如果我更改 complexType 以包含带有 xs:string 扩展名的 simpleContext,它也能正常工作。但是我从各地的实体那里得到了这个问题,其中有很多,在很多 xsd 文件中。因此,将 xml 文档中的每个元素都基于 xs:string 来解决这个问题是不可行的。

尽管 j2se 6 使用来自 apache-xerces 的 SchemaFactory,但它似乎不接受来自 xerces 的“忽略空白”功能。 (即 schemaFactory.setFeature() )

最佳答案

在使用 StAX API 进行验证之前,您可以使用 EventFilter 过滤掉空字符块:

class WhitespaceFilter implements EventFilter {
  @Override
  public boolean accept(XMLEvent event) {
    return !(event.isCharacters() && ((Characters) event)
        .isWhiteSpace());
  }
}

这可用于包装您的输入:
// strip unwanted whitespace
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLEventReader eventReader = inputFactory
    .createXMLEventReader(ReadXml.class.getResourceAsStream("level.xml"));
eventReader = inputFactory.createFilteredReader(eventReader,
    new WhitespaceFilter());

// parsing the xml
Source sourceRoot = (Source) unmarshaller.unmarshal(eventReader);

//TODO: proper error + stream handling

关于java - 验证 JAXB,但不会忽略空格,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1112896/

10-11 20:19
查看更多