使用 lxml Etree 更新 python 中的 xml 标签

Updating xml tag in python using lxml Etree

我正在尝试用另一个值更新 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>

SubElement()lxml.etree 模块中的函数)创建一个新元素,但这不是必需的。

只需获取对现有 <BasePath> 元素的引用并更新其文本内容。

from lxml import etree
 
tree = etree.parse("default.xml")
 
update = tree.find("//BasePath")
update.text = "new basepath"
 
pretty = etree.tostring(tree, encoding="unicode", pretty_print=True)
print(pretty)

输出:

<ProxyEndpoint name="default">
  <HTTPProxyConnection>
    <BasePath>new basepath</BasePath>
    <VirtualHost>https_vhost_sslrouter</VirtualHost>
    <VirtualHost>secure</VirtualHost>
  </HTTPProxyConnection>
</ProxyEndpoint>