Skip to content

Instantly share code, notes, and snippets.

@umiphos
Created June 27, 2018 15:11
Show Gist options
  • Save umiphos/0fa395c8ab1094ee4a8a16e4daab32d0 to your computer and use it in GitHub Desktop.
Save umiphos/0fa395c8ab1094ee4a8a16e4daab32d0 to your computer and use it in GitHub Desktop.
Deleting an XML element
"""We want to remove //content item, this is one way to do it."""
from lxml.etree import tostring
from lxml.objectify import fromstring
xml = '
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:getStatusCdrResponse xmlns:ns2="http://service.sunat.gob.pe">
<statusCdr>
<content/>
<statusCode>0001</statusCode>
</statusCdr>
</ns2:getStatusCdrResponse>
</S:Body>
</S:Envelope>
'
xml_obj = fromstring(lxml)
removed_item = xml_obj.xpath("//content")[0] # We know it exist, the [0] is to get the StringElement from that list
removed_item.getparent().remove(removed_item)
print(tostring(xml_obj))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment