【问题标题】:Updating xml tag in python using lxml Etree使用 lxml Etree 在 python 中更新 xml 标签
【发布时间】: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


【解决方案1】:

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

只需获取对现有 &lt;BasePath&gt; 元素的引用并更新其文本内容。

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>

【讨论】:

    猜你喜欢
    • 2017-07-20
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多