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

1 投票
1 回答
1013 浏览
提问于 2025-04-17 14:47

我想检查一个叫 sample.xml 的 XML 文件的有效性,这个文件是和 sample.dtd 关联的。但是我无法找到错误的位置,只能看到错误信息。我该怎么做呢?

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())

1 个回答

1

试着使用单独的日志条目,而不是打印整个结果,比如这样:

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

撰写回答