Holger.Joukl@LBBW.de schrieb am 11.11.20 um 15:17:
Suppose I have an element tree:
xml = lxml.etree.XML(b"<a>bla <b>bla</b> bla <c>bla</c> bla <d/> bla</a>”)
and I get all of its elements:
elems = xml.xpath(".//*”) [<Element b at 0x10d1dad70>, <Element c at 0x10d1dad20>, <Element d at 0x10d1dacd0>]
Next, I remove some element from that tree:
c = xml.find("c”) # = elems[1] c.getparent().remove(c)
How can I now test whether that element is still in the element tree?
c.getparent() # elems[1].getparent()
returns None, but is that a sure test? I can’t find documentation on how to identify elements that don’t belong to a given element tree.
IIRC: getparent() also returns None for a root element.
Let's say, any element without a parent. If an element is removed from the tree (and note that you cannot remove a root element "from its tree", because it has no parent to remove it from), then it will not have a parent afterwards any more. So this is a safe test.
As far as I remember each element always belongs to one unique tree, which gets created on-the-fly for an element that you remove from a tree.
So I don't quite see the usecase
I could imagine test cases to make use of this property, but apart from that … if an element is removed, it's removed.
you could check if c.getroottree() is the same tree object as your original/other tree (i.e. xml.getroottree()).
That seems unnecessarily complicated to me. Stefan