首页 > Python的lxml模块,无法用dtd验证xml文件是为什么?

Python的lxml模块,无法用dtd验证xml文件是为什么?

我现在想要解析一个xml文件,然后把里面的内容读取出来再转成csv文件。于是我决定用lxml模块,然而在使用的过程中,代码老是报错说有属性没有定义,可是在都DTD文件里头已经很明显的定义了,而且我也确认了dtd文件确实有导入。 我不知道这到底是什么原因,即使是把dtd文件放进测试的xml文件里头也不行。
不知道有没有人可以给我一些解决的思路,谢谢各位。

以下是相关的测试代码:

context = etree.iterparse(f, dtd_validation=True, load_dtd=True, events=("start", "end"), resolve_entities=True)
testtext = etree.XMLParser(dtd_validation=True, load_dtd=True, resolve_entities=True)

context = iter(context)
event, root = next(context)

current_tag = None
for event, elem in context:
    print elem.tag
    

运行以上代码以后就会报出以下:

lxml.etree.XMLSyntaxError: No declaration for attribute mdate of element www, line 5, column 15

可是DTD文件已经明确定义了‘www’的属性‘mdate’:

<!ELEMENT dblp (article|inproceedings|proceedings|book|incollection|phdthesis|mastersthesis|www)*>
<!ENTITY % field "author|editor|title|booktitle|pages|year|address|journal|volume|number|month|url|ee|cdrom|cite|publisher|note|crossref|isbn|series|school|chapter">
<!ELEMENT article       (%field;)*>
<!ATTLIST article
                        key CDATA #REQUIRED
                        mdate CDATA #IMPLIED
                        publtype CDATA #IMPLIED
                        reviewid CDATA #IMPLIED
                        rating CDATA #IMPLIED
>
<!ELEMENT www           (%field;)*>
<!ATTLIST www           key CDATA #REQUIRED
                        mdate CDATA #IMPLIED
                        publtype CDATA #IMPLIED
>
        

所以我不知道为什么他还是会报错说没有定义这个属性。
接下来是相关的xml测试代码:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dblp SYSTEM "dblp.dtd">
<dblp>
<www mdate="2005-10-06" key="persons/Ley93">
<author>Michael Ley</author>
<title>DBLP.uni-trier.de: Computer Science Bibliography</title>
<url>http://dblp.uni-trier.de/</url>
<year>1993</year>
</www>
<article mdate="2002-01-03" key="persons/CoddD74">
<author>E. F. Codd</author>
<author>C. J. Date</author>
<title>Interactive Support for Non-Programmers: The Relational and Network Approaches.</title>
<journal>IBM Research Report, San Jose, California</journal>
<volume>RJ1400</volume>
<month>June</month>
<year>1974</year>
</article>
</dblp>

所以基本上我整个人是处于懵逼状态的。不知道各位能不能告诉我一下到底是什么原因导致这个问题,然后可以怎么解决。 谢谢各位大大了。。。_(:зゝ∠)_

【热门文章】
【热门文章】