How do I parse XML results into an array?

Sinaesthetic picture Sinaesthetic · Nov 14, 2012 · Viewed 13.4k times · Source

I'm new to Python and need some help. The web hasn't been very helpful. Simply put, I have a web response that looks like this:

<html>
  <field>123</field>
  <field>456</field>
</html>

What I'm trying to do is take all of the contents from the field elements into an array that I can index. The end result would look like this:

myArray[0] = 123
myArray[1] = 456

and so on...

What I'm going to end up doing with this is running a random number generator to randomly pick one of the elements in this array and retrieve its value.

Is this possible? I can't seem to find a straight answer on the web, so I feel like I might be asking for the wrong thing.

Answer

aw4lly picture aw4lly · Nov 14, 2012

If you're doing simple things like that you might want to look at the ElementTree module built into python. You don't need to install anything extra, its all included in python

import xml.etree.ElementTree as ET

filename='data.txt'
tree = ET.parse(filename)
root = tree.getroot()
myArray=[]

for x in root.findall('field'):
    myArray.append(x.text)

print(myArray)