-1

Is there a smooth way to access the parent element of an element

For example:

<A>
   <B id="254">
      <Z>12.34</Z>
      <C>Lore</C>
      <D>9</D>
   </B>
</A>

For <B> I want to get <A> and for <Z>, <C>, <D> I want to get <B>

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
JME
  • 27
  • 4

1 Answers1

0

You could try using the XPath abbreviated syntax ...

This would be something like:

.//B/..

(It starts with . because ElementTree doesn't allow an absolute path on an element.)

Example:

import xml.etree.ElementTree as ET

xml = """
<A>
   <B id="254">
      <Z>12.34</Z>
      <C>Lore</C>
      <D>9</D>
   </B>
</A>
"""

root = ET.fromstring(xml)

for elem_name in ['B', 'Z']:
    # Example xpath: .//Z/..
    print(f"Parent of '{elem_name}': " + root.find(f".//{elem_name}/..").tag)

This prints:

Parent of 'B': A
Parent of 'Z': B

If you could use lxml, it has the handy method getparent() (plus full xpath 1.0 support and support of exslt extensions).

Daniel Haley
  • 51,389
  • 6
  • 69
  • 95