使用lxml处理XML中缺少的标记

时间:2016-07-18 21:49:13

标签: python xml lxml

我正在使用代码描述here解析一个巨大的xml文件,它运行正常。但是我意识到在某些情况下缺少父元素。这是一个例子:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dblp SYSTEM "dblp.dtd">
    <dblp>

    <article mdate="2011-01-11" key="journals/acta/Ernst77"> 
    <author>George W. Ernst</author>
    <title>Rules of Inference for Procedure Calls.</title>
    <journal>Acta Inf.</journal>
    <volume>8</volume> 
    <year>1977</year> 
    <pages>145-152</pages>
    <url>db/journals/acta/acta8.html#Ernst77</url>
    <ee>http://dx.doi.org/10.1007/BF00289246</ee>
    </article>

    <article mdate="2011-01-11" key="journals/acta/Pfaff83">
    <author>G&uuml;nther E. Pfaff</author>
    <title>The Construction of Operator Interfaces Based on Logical Input Devices.</title>
    <pages>151-166</pages>
    <year>1983</year>
    <volume>19</volume>
    <journal>Acta Inf.</journal>
    <url>db/journals/acta/acta19.html#Pfaff83</url>
    <ee>http://dx.doi.org/10.1007/BF00264473</ee>
    </article>
    <article mdate="2011-01-11" key="journals/acta/EngelfrietV88">
    <author>Joost Engelfriet</author>
    <author>Heiko Vogler</author>
    <title>High Level Tree Transducers and Iterated Pushdown Tree Transducers.</title>
    <pages>131-192</pages>
    <year>1988</year>
    <volume>26</volume>
    <journal>Acta Inf.</journal>
    <number>1/2</number>
    <url>db/journals/acta/acta26.html#EngelfrietV88</url>
    <ee>http://dx.doi.org/10.1007/BF02915449</ee>
    </article>

    <author>Antonio Gull&igrave;</author>
    <title>Clustering and ranking for web information retrieval: methodologies for searching the web.</title>
    <year>2008</year>
    <school>University of Pisa</school>
    <pages>1-137</pages>
    <isbn>978-3-8364-5657-9</isbn>
    <ee>http://d-nb.info/987753223</ee>

    </dblp> 

最后一条记录缺少开始和结束标记<article>

代码中的

(在链接中提供)错误来自for循环extract_paper_elements中的函数for event, element in context。这是错误:

Element dblp content does not follow the DTD, expecting (article | inproceedings | proceedings | book | incollection | phdthesis | mastersthesis | www)*, got (article article article author title year school pages isbn ee ), line 47, column 12

这种情况有解决方案吗? 我也很高兴找到这些案例的解决方案(使用bash命令或代码)。如果案例数量不多,我可以手动修复它们!

1 个答案:

答案 0 :(得分:2)

解决方案正如您所期望的那样:手动修复损坏的XML。

当您遇到任意验证错误时,没有可以自动应用的常规修复方法。可以想象一些简单的案例会被自动覆盖,但一般来说,有多种方法可以解决验证错误。您通常决定哪个是合适的并手动修复XML(或修复产生无效XML的上游系统)。

然后您再次验证并解决任何进一步的问题。这个循环重复进行,直到没有验证错误(就像修复编程语言中的语法问题一样)。