I am using the builtin Python ElementTree module. It is straightforward to access children, but what about parent or sibling nodes? - can this be done efficiently without traversing the entire tree?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Vinay's answer should still work, but for Python 2.7+ and 3.2+ the following is recommended:
getiterator()
is deprecated in favor ofiter()
, and it's nice to use the newdict
list comprehension constructor.Secondly, while constructing an XML document, it is possible that a child will have multiple parents, although this gets removed once you serialize the document. If that matters, you might try this:
Look at the 19.7.2.2. section: Supported XPath syntax ...
Find node's parent using the path:
As mentioned in Get parent element after using find method (xml.etree.ElementTree) you would have to do an indirect search for parent. Having xml:
Assuming you have created etree element into
xml
variable, you can use:Resulting in:
Higher parent would be found as:
secondparent=xml.find('.//c/../..')
being<Element 'a' at 0x00XXXXXX>
You can use xpath
...
notation in ElementTree.If you are using lxml, I was able to get the parent element with the following:
This will raise a
StopIteration
exception if the element doesn't have ancestors - so be prepared to catch that if you may run into that scenario.Another way if just want a single subElement's parent and also known the subElement's xpath.