次のJavaコードを使用して、次のXMLに対して以下のDTDを検証しようとしています。 (JDK 8 - すべてのファイルがクラスパスで正しく見つかりました)。それは以下の例外を投げている。有効なXMLとDTDが検証されない
xtdにdtdを埋め込むと、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)