繁体   English   中英

新增中 <root> 使用Python标记为XML文档

[英]Adding <root> tag to XML doc with Python

尝试在200万行XML文件的开头和结尾添加根标签,以便可以使用我的Python代码正确处理该文件。

我尝试使用上一篇文章中的代码,但出现错误“ XMLSyntaxError:文档末尾,第__行,第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>

我怀疑这种策略有效,因为在最高级别只有一个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;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM