1

I have the following XML file:

<main>
  <node>
    <party iot="00">Big</party>
    <children type="me" value="3" iot="A">
       <p>
          <display iot="B|S">
             <figure iot="FF"/>
          </display>
       </p>
       <li iot="C"/>
       <ul/>
    </children>
  </node>
  <node>
    <party iot="01">Small</party>
    <children type="me" value="1" iot="N">
       <p>
          <display iot="T|F">
             <figure iot="MM"/>
          </display>
       </p>
    </children>
  </node>
</main>

How can I retrieve all values of iot attribute from sub-elements of children of the first node? I need to retrieve the values of iot as a list.

The expected result:

iot_list = ['A','B|S','FF','C']

This is my current code:

import xml.etree.ElementTree as ET

mytree = ET.parse("file.xml")
myroot = mytree.getroot()
list_nodes = myroot.findall('node')
for n in list_nodes:
   # ???
Fluxy
  • 2,838
  • 6
  • 34
  • 63
  • This is not well-informed XML: `
    `. Assuming it is typo, consider fixing here in post. If not, check its source. Avoid [building XML with string concatenation](https://stackoverflow.com/questions/3034611/whats-so-bad-about-building-xml-with-string-concatenation).
    – Parfait Apr 19 '22 at 00:06
  • 2
    Consider Python's 3rd party, `lxml`, that supports the full XPath 1.0 and can easily return all iot attributes of children's descendants: `descendant::*/@iot`. – Parfait Apr 19 '22 at 00:11
  • @Parfait: Thanks, yes, this was typo. Thanks for noticing. I've just fixed it. – Fluxy Apr 21 '22 at 08:34
  • The `` element (in both ``s doesn't have any children; `

    ` and `

  • ` are its siblings.
  • – Jack Fleeting Apr 21 '22 at 18:09
  • @JackFleeting I see what you mean. I've just updated the example. Thanks. – Fluxy Apr 22 '22 at 10:41
  • That's better! Also - it seems you don't only want to "retrieve all values of iot attribute from **sub-elements** of children" but also from the `` element itself (`A`); correct? – Jack Fleeting Apr 22 '22 at 12:19
  • @JackFleeting: Right. – Fluxy Apr 24 '22 at 12:23