0

这是 XML 模式:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="products">
    <xs:complexType>
      <xs:sequence minOccurs="0" maxOccurs="unbounded">
        <xs:element name="product" type="ProductType"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:complexType name="ProductType">
    <xs:sequence>
      <xs:element name="id" type="xs:long" />
      <xs:element name="name" type="xs:string" />
      <xs:element name="price" type="xs:decimal" />
    </xs:sequence>
  </xs:complexType>

</xs:schema>

经过一致性验证的 XML 文件:

<?xml version="1.0" ?>
<products>
  <product>
    <invalid_tag>32342</invalid_tag>
    <name>Some name</name>
    <price>3.89</price>
  </product>
</products>

使用 XML 并应测试一致性的 Java 代码:

SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(false);
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
factory.setSchema(schemaFactory.newSchema(new File(xmlSchema)));
parser = factory.newSAXParser();
ProductsSaxHandler handler = new ProductsSaxHandler();
parser.parse(new File(xmlFile), handler);

但我没有任何例外。怎么了?

4

1 回答 1

3

我看到您正在使用 custom ProductsSaxHandler

您没有为它提供代码,但很可能在ErrorHandler调用接口的通知方法之一时它不会引发异常。

确保覆盖error,fatalErrorwarning方法ProductSaxHandler来抛出异常。

于 2012-06-26T22:16:47.723 回答