user2755209
user2755209

Reputation: 85

Parsing XML in Python with Loop

I am new to Python.

I have a piece of python I have written to take out a data element I need from an XML that I have. The problem is I do not know how to repeat it to get out all the elements that I need.

import xml.etree.ElementTree as ET
import lxml.etree


doc = lxml.etree.parse('datafiles.xml')
total_datasets = doc.xpath('count//driversUsed)')


tree = ET.parse('datafiles.xml')
root = tree.getroot()

alias = root[1]
dataset = alias[0]
current = dataset[0]

print(current.text) 

So right now the current has the first value that I need but I need to do a loop where dataset = alias[1], dataset = alias[2] .... dataset = alias[total_datasets].

I've done a little bit of looping but I don't know how to do it where the variable is not just an integer but has the [] with the integer inside.

Upvotes: 2

Views: 485

Answers (1)

furas
furas

Reputation: 143187

Use for and you don't need total_datasets

for dataset in alias:
    current = dataset[0]
    print(current.text) 

It is basic knowledge so better find some Python Tutorial.

Upvotes: 2

Related Questions