【发布时间】:2017-04-24 18:38:12
【问题描述】:
尝试将根标记添加到 2 百万行 XML 文件的开头和结尾,以便可以使用我的 Python 代码正确处理该文件。
我尝试使用 previous post 中的此代码,但我收到错误“XMLSyntaxError: Extra content at the end of the document, line __, column 1”
我该如何解决这个问题?或者有没有更好的方法在我的大型 XML 文档的开头和结尾添加根标记?
import lxml.etree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
newroot = ET.Element("root")
newroot.insert(0, root)
print(ET.tostring(newroot, pretty_print=True))
我的测试 XML
<pub>
<ID>75</ID>
<title>Use of Lexicon Density in Evaluating Word Recognizers</title>
<year>2000</year>
<booktitle>Multiple Classifier Systems</booktitle>
<pages>310-319</pages>
<authors>
<author>Petr Slavík</author>
<author>Venu Govindaraju</author>
</authors>
</pub>
<pub>
<ID>120</ID>
<title>Virtual endoscopy with force feedback - a new system for neurosurgical training</title>
<year>2003</year>
<booktitle>CARS</booktitle>
<pages>782-787</pages>
<authors>
<author>Christos Trantakis</author>
<author>Friedrich Bootz</author>
<author>Gero Strauß</author>
<author>Edgar Nowatius</author>
<author>Dirk Lindner</author>
<author>Hüseyin Kemâl Çakmak</author>
<author>Heiko Maaß</author>
<author>Uwe G. Kühnapfel</author>
<author>Jürgen Meixensberger</author>
</authors>
</pub>
【问题讨论】:
-
您的 test.xml 文档没有根元素,因此它不是真正的 XML,因此无法解析。
-
@mzjn 你没抓住重点,我试图添加根标签以便它可以被读取为 XML。
-
好吧,我的意思是您在添加根元素之前尝试将 test.xml 解析为 XML。这就是你得到错误的原因。
标签: python xml elementtree