In [1]:
import xml.etree.ElementTree as ET
tree = ET.parse('demo.xml')
root = tree.getroot()

In [4]:
root


Out[4]:
<Element 'bookstore' at 0x7fb08863d3b8>

In [7]:
ET.dump(root)


<bookstore xmlns:ns0="uri:mynamespace" specialty="novel">
  <book style="autobiography">
    <author>
      <first-name>Joe</first-name>
      <last-name>Bob</last-name>
      <award>Trenton Literary Review Honorable Mention</award>
    </author>
    <price>12</price>
  </book>
  <book style="textbook">
    <author>
      <first-name>Mary</first-name>
      <last-name>Bob</last-name>
      <publication>Selected Short Stories of
        <first-name>Mary</first-name>
        <last-name>Bob</last-name>
      </publication>
    </author>
    <editor>
      <first-name>Britney</first-name>
      <last-name>Bob</last-name>
    </editor>
    <price>55</price>
  </book>
  <magazine frequency="monthly" style="glossy">
    <price>2.50</price>
    <subscription per="year" price="24" />
  </magazine>
  <book id="myfave" style="novel">
    <author>
      <first-name>Toni</first-name>
      <last-name>Bob</last-name>
      <degree from="Trenton U">B.A.</degree>
      <degree from="Harvard">Ph.D.</degree>
      <award>Pulitzer</award>
      <publication>Still in Trenton</publication>
      <publication>Trenton Forever</publication>
    </author>
    <price exchange="0.7" intl="Canada">6.50</price>
    <excerpt>
      <p>It was a dark and stormy night.</p>
      <p>But then all nights in Trenton seem dark and
      stormy to someone who has gone through what
      <emph>I</emph> have.</p>
      <definition-list>
        <term>Trenton</term>
        <definition>misery</definition>
      </definition-list>
    </excerpt>
  </book>
  <ns0:book price="29.50" style="leather">
    <ns0:title>Who's Who in Trenton</ns0:title>
    <ns0:author>Robert Bob</ns0:author>
  </ns0:book>
</bookstore>

In [8]:
root.findall(".")


Out[8]:
[<Element 'bookstore' at 0x7fb08863d3b8>]

In [12]:
root.findall("./book")


Out[12]:
[<Element 'book' at 0x7fb0885ed278>,
 <Element 'book' at 0x7fb0885eda98>,
 <Element 'book' at 0x7fb0885edf48>]

In [19]:
for elemento in root.findall("./book"):
    print (elemento.tag, elemento.attrib)


book {'style': 'autobiography'}
book {'style': 'textbook'}
book {'style': 'novel', 'id': 'myfave'}

In [26]:
root[0][0][1].text


Out[26]:
'Bob'

In [32]:
root[3][1].text


Out[32]:
'6.50'

In [40]:
for elemento in root.findall(".//author"):
    print (elemento.tag,elemento.find('first-name').text,elemento.find('last-name').text)


author Joe Bob
author Mary Bob
author Toni Bob

In [45]:
for elemento in root.findall(".//author"):
    try:
        print (len(elemento))
        print (elemento.tag,elemento.find('first-name').text,elemento.find('last-name').text)
    except:
        print (elemento.tag,elemento.find('first-name').text,elemento.find('degree').text)


3
author Joe Bob
3
author Mary Bob
7
author Toni Bob

In [ ]: