[newbie] Removing all elements that match string?

Hello, I'm only getting started with (l)xml, and was curious to know if someone had an example of how to remove all items in an XML file that match the following string: ^\t*<ele>100.25</ele>\r\n Thank you.

Are you looking for something like this: # ------------------------------ def remove(root, tag, text): items = root.xpath(f'.//{tag}') for item in items: if item.text == text: parent = item.getparent() parent.remove(item) return root # ------------------------------ Also look at element.iter, element.iterdescendants, etc. Dave On Fri 30 Jul 2021 11:02:59 AM PDT, Gilles wrote:
-- Dave Kuhlman http://www.davekuhlman.org

Thanks. I need to read in a GPX file, remove all occurences of the "<time>" element, regardless of what they contain, and write back the edited data: ====== import lxml.etree as et def remove(root, tag, text): items = root.xpath(f'.//{tag}') for item in items: if item.text == text: parent = item.getparent() parent.remove(item) return root tree = et.parse("input.gpx") remove(tree,"time","") #Still here print(et.tostring(tree, pretty_print=True)) with open("output.gpx", 'wb') as doc: doc.write(et.tostring(tree, pretty_print = True)) ====== I'll read up on element.iter, element.iterdescendants, etc. On 30/07/2021 21:13, Dave Kuhlman wrote:
org/mailman3/lists/lxml.python.org/ Member address: dkuhlman@davekuhlman.org

Are you looking for something like this: # ------------------------------ def remove(root, tag, text): items = root.xpath(f'.//{tag}') for item in items: if item.text == text: parent = item.getparent() parent.remove(item) return root # ------------------------------ Also look at element.iter, element.iterdescendants, etc. Dave On Fri 30 Jul 2021 11:02:59 AM PDT, Gilles wrote:
-- Dave Kuhlman http://www.davekuhlman.org

Thanks. I need to read in a GPX file, remove all occurences of the "<time>" element, regardless of what they contain, and write back the edited data: ====== import lxml.etree as et def remove(root, tag, text): items = root.xpath(f'.//{tag}') for item in items: if item.text == text: parent = item.getparent() parent.remove(item) return root tree = et.parse("input.gpx") remove(tree,"time","") #Still here print(et.tostring(tree, pretty_print=True)) with open("output.gpx", 'wb') as doc: doc.write(et.tostring(tree, pretty_print = True)) ====== I'll read up on element.iter, element.iterdescendants, etc. On 30/07/2021 21:13, Dave Kuhlman wrote:
org/mailman3/lists/lxml.python.org/ Member address: dkuhlman@davekuhlman.org
participants (2)
-
Dave Kuhlman
-
Gilles