Reputation: 25
The following code works fine in oracle jre but not in ibm ones (try the version 5, 6 and 7). The code just validate some xml against a xsd.
Is it a known bug ? Is there a magic property or feature to set ?
public static void main(String[] args) throws Exception {
String xsd = "<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"+
"<xsd:element name=\"comment\" type=\"xsd:string\"/>" +
"</xsd:schema>";
String xml = "<comment>test</comment>";
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema( new StreamSource(new StringReader(xsd)));
Validator validator = schema.newValidator();
Source source = new DOMSource(document);
validator.validate(source);
System.out.println("ok");
}
The exception :
Exception in thread "main" org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'comment'.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source)
I can bypass this bug, if I transform my document to a String and using a StreamSource. But i'd like to validate the document directly. This example could not be simpler and should work on IBM JRE, isn't it ?
Upvotes: 1
Views: 389
Reputation: 159086
You need to call DocumentBuilderFactory.setNamespaceAware(true)
.
This is necessary because you are using an XML Schema, which is namespace based, even when there is no namespace url. The Oracle JRE is apparently lenient and supported it without that attribute, while the IBM JRE is a bit more strict, i.e. <comment>
without a namespace (false) and <comment>
with no namespace (true) are considered different.
Change your code to:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Upvotes: 3