I am trying to validate the following xml against the following DTD using the following Java code. (JDK 8 - All files are correctly found in the classpath). It is throwing the following exceptions.
Everything seems to be correct, and the IDE is not showing any red underlines when I embed the dtd in the xml, so I assume all syntax is correct. The error message says the exception is line number 1. When I add a blank line to the top of the DTD it changes that to line number 2, so I am pretty sure it is not liking the DTD. I tried the same using examples downloaded over the internet, and get the same issue.
What am I doing wrong???
test.xml:
<?xml version="1.0" encoding="UTF-8"?>
<properties>
<property>key1=value1</property>
</properties>
test.dtd:
<!ELEMENT properties (property)*>
<!ELEMENT property (#PCDATA)>
Validate.java:
public static void validateXml(String xmlFile, String dtdFile)
throws SAXException, IOException, ParserConfigurationException, URISyntaxException
{
URL dtdUrl = XmlUtils.class.getClassLoader().getResource(dtdFile);
System.out.println("DTD:\n" + new String(Files.readAllBytes(Paths.get(dtdUrl.toURI()))));
// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
URL xmlUrl = XmlUtils.class.getClassLoader().getResource(xmlFile);
System.out.println("XML:\n" + new String(Files.readAllBytes(Paths.get(xmlUrl.toURI()))));
Document document = parser.parse(xmlUrl.openStream());
// create a SchemaFactory capable of understanding WXS schemas
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// load a WXS schema, represented by a Schema instance
Reader dtdReader = new URLReader(dtdUrl);
Source schemaFile = new StreamSource(dtdReader);
Schema schema = factory.newSchema(schemaFile);
// create a Validator instance, which can be used to validate an instance document
Validator validator = schema.newValidator();
// validate the DOM tree
validator.validate(new DOMSource(document));
}
System.out:
DTD:
<!ELEMENT properties (property)*>
<!ELEMENT property (#PCDATA)>
XML:
<?xml version="1.0" encoding="UTF-8"?>
<properties>
<property>key1=value1</property>
</properties>
Exception in thread "main" org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 3;
The markup in the document preceding the root element must be well-formed.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper
.createSAXParseException(ErrorHandlerWrapper.java:203)