0

Here is XML Schema:

<?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 file that is validated for conformance:

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

Java code that works with XML and should test conformance:

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);

But I don't get any exception. What is wrong?

Andrei Botalov
  • 20,686
  • 11
  • 89
  • 123

1 Answers1

3

I see that you are using custom ProductsSaxHandler.

You did not provide code for it, but most likely it does not throw an exception when one of the notification methods of ErrorHandler interface is called.

Make sure you override error, fatalError and warning methods of ProductSaxHandler to throw an exception.

Alexander Pogrebnyak
  • 44,836
  • 10
  • 105
  • 121