Arunava Paul
Arunava Paul

Reputation: 111

Updating xml tag in python using lxml Etree

I'm trying to update a single tag in my xml file with another value. I'm using lxml module in python.

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()

I'm getting AttributeError: 'lxml.etree._Element' object has no attribute 'SubElement' error. I just need the tag updated in xml. Below is the xml.

 <ProxyEndpoint name="default">
  <HTTPProxyConnection>
    <BasePath>/v2/test</BasePath>
    <VirtualHost>https_vhost_sslrouter</VirtualHost>
    <VirtualHost>secure</VirtualHost>
  </HTTPProxyConnection>
 </ProxyEndpoint>

Upvotes: 1

Views: 892

Answers (1)

mzjn
mzjn

Reputation: 50947

SubElement() (a function in the lxml.etree module) creates a new element, but that is not necessary.

Just get a reference to the existing <BasePath> element and update its text content.

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)

Output:

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

Upvotes: 1

Related Questions