"lxml.etree._ElementTree"对象没有属性"insert"



我正试图使用glob解析我的.xml文件,然后使用etree向我的.xml添加更多代码。然而,在使用doc insert时,我不断收到一个错误,说对象没有属性插入。有人知道我如何有效地将代码添加到.xml中吗?

from lxml import etree
path = "D:/Test/"
for xml_file in glob.glob(path + '/*/*.xml'):
doc = etree.parse(xml_file)
new_elem = etree.fromstring("""<new_code abortExpression=""
elseExpression=""
errorIfNoMatch="false"/>""")
doc.insert(1,new_elem)
new_elem.tail = "n"

我原来的xml是这样的:

<data>
<assesslet index="Test" hash-uptodate="False" types="TriggerRuleType" verbose="True"/>
</data>

我想把它修改成这样:

<data>
<assesslet index="Test" hash-uptodate="False" types="TriggerRuleType" verbose="True"/>
<new_code abortExpression="" elseExpression="" errorIfNoMatch="false"/>
</data>

问题是,在开始修改文档之前,您需要从文档中提取根:修改doc.getroot()而不是doc

这对我有效:

from lxml import etree
xml_file = "./doc.xml"
doc = etree.parse(xml_file)
new_elem = etree.fromstring("""<new_code abortExpression=""
elseExpression=""
errorIfNoMatch="false"/>""")
root = doc.getroot()
root.insert(1, new_elem)
new_elem.tail="n"

要将结果打印到文件中,可以使用doc.write():

doc.write("doc-out.xml", encoding="utf8", xml_declaration=True)

注意xml_declaration=True参数:它告诉doc.write()生成<?xml version='1.0' encoding='UTF8'?>头。

最新更新