不久前,我尝试做类似的事情,但无法找到解决方案。我终于编写了下面的脚本,它打开 XML 文件并使用正则表达式查找 DTD。它还具有在命令行上采用 DTD 路径的覆盖,这是我的要求。
如果 lxml 处理嵌套的 DTD,那么下面的代码应该适合您。
老实说,我认为自己阅读文件有点小技巧,但这是我找到的唯一方法。
import re
import sys
import os.path
import codecs
from lxml import etree
def main(args):
if len(args)<1:
print("Not enough arguments given. Expected:")
print("\tvalidatexml <xml file name> [<dtd file name>]\n")
exit(1)
dtdRe = re.compile('.*<!DOCTYPE .* ["\'](.*\.dtd)["\']>.*')
theDtd = None
inFile = args[0]
fdir = os.path.abspath(os.path.dirname(inFile))
if len(args)==2:
theDtd = os.path.abspath(args[1])
else:
with codecs.open(args[0], 'r', 'utf-8') as inf:
for ln in inf:
mtch = dtdRe.match(ln)
if mtch:
if os.path.isabs(mtch.group(1)):
theDtd = mtch.group(1)
else:
theDtd = os.path.abspath(fdir + '/' + mtch.group(1))
break
if theDtd is None:
print("No DTD specified!")
exit(2)
if not os.path.exists(theDtd):
print("The DTD ({}) does not exist!".format(theDtd))
exit(3)
print('Using DTD:', theDtd)
parser = etree.XMLParser(dtd_validation=True)
dtd = etree.DTD(open(theDtd))
tree = etree.parse(args[0])
valid = dtd.validate(tree)
if (valid):
print("XML was valid!")
else:
print("XML was not valid:")
print(dtd.error_log.filter_from_errors())
if __name__ == '__main__':
main(sys.argv[1:])