0
我正在嘗試使用以下Java代碼針對以下DTD驗證以下xml。 (JDK 8 - 在類路徑中正確找到所有文件)。它拋出以下例外。驗證有效的XML和DTD
一切似乎都是正確的,並且當我將dtd嵌入到xml中時,IDE未顯示任何紅色下劃線,所以我假設所有語法都是正確的。該錯誤消息說異常是行號1.當我向DTD的頂部添加一個空行時,它將它更改爲行號2,所以我非常確定它不喜歡DTD。我嘗試使用通過互聯網下載的示例,並得到相同的問題。
我在做什麼錯?
的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)