Marco
Marco

Reputation: 1235

XML parsing python nested

I have the following XML file:

<annotations count="1">
  <track id="0" label="Machine">
    <box frame="0" ><attribute id="8">act1</attribute></box>
    <box frame="1" ><attribute id="8">act2</attribute></box>
    <box frame="2" ><attribute id="8">act1</attribute></box>
  </track>
</annotations>

I want to extract the frame and the action inside attribute. For example i would like to have (frame: 0 , act1), (frame: 1 , act2) ... Right now what I am doing is

root = xml.etree.ElementTree.parse(xml_file_path).getroot()

for track in root.iter('track'):
  for box in track.iter('box'):
    frame = box.get('frame')

How can I obtain also the corresponding attribute ( act1, ..., act 1) ?

Upvotes: 0

Views: 63

Answers (2)

Eliyah Afzal
Eliyah Afzal

Reputation: 36

You can also use array notation which could be useful if you are scraping or putting it in a massive loop

root[0][0][0].text

root[0][0][1].text and so on

Upvotes: 1

Uli Sotschok
Uli Sotschok

Reputation: 1236

You can access the <attribute id="8">act1</attribute> with

box.find('attribute')

To get the act you use:

>>>box.find('attribute').text
act1 # or act2

The python docs are a very good resource: https://docs.python.org/2/library/xml.etree.elementtree.html

Upvotes: 1

Related Questions