如何使用Python中的lxml-dtd.validate函数获取xml文件的错误位置



我想检查与sample.dtd关联的xml文件sample.xml的有效性。但我无法获得错误位置。我只能收到错误信息。我该怎么做?

import lxml.etree as ET
import codecs
f = codecs.open('sample.dtd')
dtd = ET.DTD(f)
root = ET.parse('newace_JK.xml')
print(dtd.validate(root))
print(dtd.error_log.filter_from_errors())

尝试使用单个日志条目,而不是打印整个结果,例如

for error in dtd.error_log.filter_from_errors():
    print(error.message)
    print(error.line)
    print(error.column)

参见http://lxml.de/api/lxml.etree._LogEntry-class.html

最新更新