我必须从DTD文件创建一些用于XML生成的Java类。
我使用了jxc实用程序:
xjc -dtd -d generatedsrc -p com.examples log4j.dtd
我可以生成xml,但是接收者拒绝了它,除此DTD之外我没有其他信息。如何针对XML验证DTD? 例如,可以在DTD中定义一个在编组之前未在对象中设置的必填字段,如何找到丢失的内容?
答案 0 :(得分:1)
有一些针对xml验证DTD的示例。为了方便起见,我将在此处粘贴一个,但最后还要粘贴链接。
对于包含dtd的给定xml,invalid_dtd.xml:
<?xml version="1.0"?>
<!-- invalid_dtd.xml
- Copyright (c) 2002-2014 HerongYang.com, All Rights Reserved.
-->
<!DOCTYPE dictionary [
<!ELEMENT dictionary (note, word+)>
<!ELEMENT note ANY>
<!ELEMENT word (update?, name, definition+, usage*)>
<!ELEMENT update EMPTY>
<!ATTLIST update
date CDATA #REQUIRED
editor CDATA #IMPLIED
>
<!ELEMENT name (#PCDATA)>
<!ATTLIST name is_acronym (true | false) "false">
<!ELEMENT definition (#PCDATA)>
<!ELEMENT usage (#PCDATA | i)*>
<!ELEMENT i (#PCDATA)>
<!ENTITY herong "Dr. Herong Yang">
]>
<dictionary>
<note>Copyright (c) 2014 by &herong;</note>
<word>
<name is_acronym="true" language="EN">POP</name>
<definition>Post Office Protocol</definition>
<definition>Point Of Purchase</definition>
</word>
<word>
<update date="2014-12-23"/>
<name is_acronym="yes">XML</name>
<definition>eXtensible Markup Language</definition>
<note>XML comes from SGML</note>
</word>
<word>
<update editor="Herong Yang"/>
<name>markup</name>
<definition>The amount added to the cost price to calculate
the selling price - <i>Webster</i></definition>
</word>
</dictionary>
运行一些检查的简单类:
public class DOMValidator {
public static void main(String[] args) {
try {
File x = new File("invalid_dtd.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setValidating(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
ErrorHandler h = new MyErrorHandler();
documentBuilder.setErrorHandler(h);
documentBuilder.parse(x);
} catch (ParserConfigurationException e) {
System.out.println(e.toString());
} catch (SAXException e) {
System.out.println(e.toString());
} catch (IOException e) {
System.out.println(e.toString());
}
}
private static class MyErrorHandler implements ErrorHandler {
public void warning(SAXParseException e) throws SAXException {
System.out.println("Warning: ");
printInfo(e);
}
public void error(SAXParseException e) throws SAXException {
System.out.println("Error: ");
printInfo(e);
}
public void fatalError(SAXParseException e)
throws SAXException {
System.out.println("Fattal error: ");
printInfo(e);
}
private void printInfo(SAXParseException e) {
System.out.println(" Public ID: "+e.getPublicId());
System.out.println(" System ID: "+e.getSystemId());
System.out.println(" Line number: "+e.getLineNumber());
System.out.println(" Column number: "+e.getColumnNumber());
System.out.println(" Message: "+e.getMessage());
}
}
}
也许您可以使用它吗?
原始来源:http://www.herongyang.com/XML/DTD-Validation-of-XML-with-DTD-Using-DOM.html