【发布时间】:2021-07-14 08:53:31
【问题描述】:
我正在尝试用另一个值更新我的 xml 文件中的单个标签。我在 python 中使用 lxml 模块。
bplocation = os.getcwd()+"/apiproxy/proxies";
tree = lxml.etree.parse(bplocation+'/default.xml');
root = tree.getroot();
update = lxml.etree.SubElement(root, "BasePath");
update.text = "new basepath";
root.SubElement('BasePath',update);
pretty = lxml.etree.tostring(root, encoding="unicode", pretty_print=True);
f = open("test.xml", "w")
f.write(pretty)
f.close()
我收到 AttributeError: 'lxml.etree._Element' object has no attribute 'SubElement' 错误。 我只需要在 xml 中更新标签。 下面是xml。
<ProxyEndpoint name="default">
<HTTPProxyConnection>
<BasePath>/v2/test</BasePath>
<VirtualHost>https_vhost_sslrouter</VirtualHost>
<VirtualHost>secure</VirtualHost>
</HTTPProxyConnection>
</ProxyEndpoint>
【问题讨论】:
-
root.SubElement('BasePath',update)是什么意思? -
行尾不需要分号
-
'lxml.etree._Element' object has no attribute 'SubElement'意味着你做something_of_type__Element.SubElement。在这种情况下,这可能意味着root.SubElement('BasePath',update)行(下次请标记哪一行抛出错误......)有点......无用和错误 -
是的 root.SubElement 正在引发错误。删除此行会打印整个文件,但我的更新不会发生
标签: python lxml elementtree