1

I wrote a python script that returns xml file tag values. It goes through the file by index. How can I check if an index exists?

This is the basic blueprint.

tree = ET.parse(file)
root = tree.getroot()
root[0][1][0].text
Michael
  • 109
  • 1
  • 1
  • 13

1 Answers1

1

I am not sure what are you trying to achive. As I understand you are parsing some XML and you are trying to get text from one of xml element basing on indexes. I think you could use XPath searching instead. It works even better if you use lxml module for parsing xmls instead of xml. Here is description of XPath usage in lxml.

Anyway, if you really prefer using indexes, you do not have to check if element exists under specific index. Use try, except block instead to catch errors if index does not exists.

This answers provides some details why you should use this approach.

And your code could look more or less like this:

tree = ET.parse(file)
root = tree.getroot()
try:
     text = root[0][1][0].text 
except IndexError as e:
     #do something to handle error
     pass
running.t
  • 5,329
  • 3
  • 32
  • 50