【问题标题】:Adding <root> tag to XML doc with Python使用 Python 将 <root> 标记添加到 XML 文档
【发布时间】: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&iacute;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&szlig;</author>
        <author>Edgar Nowatius</author>
        <author>Dirk Lindner</author>
        <author>H&uuml;seyin Kem&acirc;l &Ccedil;akmak</author>
        <author>Heiko Maa&szlig;</author>
        <author>Uwe G. K&uuml;hnapfel</author>
        <author>J&uuml;rgen Meixensberger</author>
    </authors>
</pub>

【问题讨论】:

  • 您的 test.xml 文档没有根元素,因此它不是真正的 XML,因此无法解析。
  • @mzjn 你没抓住重点,我试图添加根标签以便它可以被读取为 XML。
  • 好吧,我的意思是您在添加根元素之前尝试将 test.xml 解析为 XML。这就是你得到错误的原因。

标签: python xml elementtree


【解决方案1】:

我怀疑该策略有效,因为最高级别只有一个 A 元素。幸运的是,即使有 200 万行,也可以轻松添加所需的行。

在执行此操作时,我注意到lxml 解析器似乎无法处理重音字符。我在那里添加了代码来对它们进行英语化。

import re

def anglicise(matchobj): return matchobj.group(0)[1]

outputFilename = 'result.xml'

with open('test.xml') as inXML, open(outputFilename, 'w') as outXML:
    outXML.write('<root>\n')
    for line in inXML.readlines():
        outXML.write(re.sub('&[a-zA-Z]+;',anglicise,line))
    outXML.write('</root>\n')

from lxml import etree

tree = etree.parse(outputFilename)
years = tree.xpath('.//year')
print (years[0].text)

编辑:将anglicise 替换为此版本以避免替换&amp;amp;

def anglicise(matchobj): 
    if matchobj.group(0) == '&amp;':
        return matchobj.group(0)
    else:
        return matchobj.group(0)[1]

【讨论】:

  • 太棒了!我得到了一个包含所有内容的文件输出,但是,我在较大的 XML 文件中有一些条目,其中 &amp;amp; 用于 '&' ,并且代码正在将它们转换为 'a' 字符。我不太明白你代码的outXML.write(re.sub('&amp;[a-z]+;',anglicise,line)) 部分,我该如何调整它来处理&?
  • 对不起,最后一件事,我的代码现在卡在第二位,但不是第一作者的名字中带有&amp;szlig; 字符。我在我的(编辑的)问题中附加了 xml 节点。对我来说似乎很奇怪,它不会在第一次停止,但第二次会抛出错误
  • 我已经更改了正则表达式。
猜你喜欢
  • 2011-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多