xmllint:如何使用本地DTD文件验证XML

Eri*_* H. 15 xml dtd file local xmllint

我有一个本地DTD文件test.dtd.内容是:

<!DOCTYPE coord [
<!ELEMENT coord (date)>
<!ELEMENT date (#PCDATA)>
]>
Run Code Online (Sandbox Code Playgroud)

我想使用xmllint验证XML.此XML中没有DOCTYPE:

<?xml version="1.0" encoding="x-mac-roman"?>
<coord>
    <date>20150312</date>
</coord>
Run Code Online (Sandbox Code Playgroud)

如果我将DTD块作为第二行插入到我的XML文件的副本中并使用:

xmllint --valid --noout my2.xml
Run Code Online (Sandbox Code Playgroud)

但是当我尝试:

xmllint --loaddtd test.dtd --valid --noout my.xml

xmllint --dtdvalid test.dtd --noout my.xml
Run Code Online (Sandbox Code Playgroud)

两者都不起作用.结果是:

test.dtd:1: parser error : Content error in the external subset
<!DOCTYPE coord [
^
test.dtd:1: parser error : Content error in the external subset
<!DOCTYPE coord [
^
Could not parse DTD test.dtd
Run Code Online (Sandbox Code Playgroud)

任何的想法 ?看来我的XML 必须包含一个DOCTYPE行(带有SYSTEM关键字)来引用我想要避免的外部DOCTYPE文件.请参阅:http://www.w3schools.com/dtd/

有没有修改XML的解决方案?

Mat*_*ler 23

首先,外部DTD不需要<!DOCTYPE前导码 - 从DTD文件中删除它:

<!ELEMENT coord (date)>
<!ELEMENT date (#PCDATA)>
Run Code Online (Sandbox Code Playgroud)

然后,--loaddtd 获取外部DTD,这与针对外部DTD进行验证不同.使用以下--dtdvalid选项:

$ xmllint --noout --dtdvalid test.dtd test.xml
Run Code Online (Sandbox Code Playgroud)

如果XML文档有效,xmllint将不会输出任何内容(因为--noout).如果您将DTD更改为,请说:

<!ELEMENT coord (date,other)>
<!ELEMENT date (#PCDATA)>
Run Code Online (Sandbox Code Playgroud)

输出将是

$ xmllint --noout --dtdvalid test.dtd test.xml
test.xml:2: element coord: validity error : Element coord content does not follow the DTD, expecting (date , other), got (date )
Document test.xml does not validate against test.dtd
Run Code Online (Sandbox Code Playgroud)

NMTXMLSoft的doc页面上查找更多信息.