我正在尝试编写一个验证脚本,它将根据nitf dtd来验证xml,http://www.iptc.org/std/NITF/3.4/specification/dtd/nitf-3-4.dtd。基于this post我提出了以下简单的脚本来验证nitf xml文档。下面是我在运行脚本时收到的错误消息,这不是很好的描述,而且很难调试。如有任何帮助,我们将不胜感激。

#!/usr/bin/env python


def main():
    from lxml import etree, objectify
    from StringIO import StringIO

    f = open('nitf_test.xml')
    xml_doc = f.read()
    f.close()

    f = open('nitf-3-4.dtd')
    dtd_doc = f.read()
    f.close()

    dtd = etree.DTD(StringIO(dtd_doc))
    tree = objectify.parse(StringIO(xml_doc))
    dtd.validate(tree)


if __name__ == '__main__':

    main()

回溯错误消息:
Traceback (most recent call last):
  File "./test_nitf_doc.py", line 23, in <module>
    main()
  File "./test_nitf_doc.py", line 16, in main
    dtd = etree.DTD(StringIO(dtd_doc))
  File "dtd.pxi", line 43, in lxml.etree.DTD.__init__ (src/lxml/lxml.etree.c:126056)
  File "dtd.pxi", line 117, in lxml.etree._parseDtdFromFilelike (src/lxml/lxml.etree.c:126727)
lxml.etree.DTDParseError: error parsing DTD

如果我换线:
dtd = etree.DTD(StringIO(dtd_doc))

到:
dtd = etree.DTD(dtd_doc)

我得到的错误是:
lxml.etree.DTDParseError: failed to load external entity "NULL"

最佳答案

我看了一下nitf-3-4.dtd,发现它引用了一个可以downloaded at this link的外部模块xhtml-ruby-1.mod。这需要存在于当前目录中,以便dtd解析器可以加载它。
完整的工作示例(假设您手头有一个有效的NITF文档):

% wget http://www.iptc.org/std/NITF/3.4/specification/dtd/nitf-3-4.dtd
% wget http://www.iptc.org/std/NITF/3.4/specification/dtd/xhtml-ruby-1.mod

Python代码:
from lxml import etree, objectify
dtd = etree.DTD(open('nitf-3-4.dtd', 'rb'))
tree = objectify.parse(open('nitf_test.xml', 'rb'))
print dtd.validate(tree)

输出:
% python nitf_test.py
True

09-15 22:50