0

i am really new to python. this is actually my first script with it and most of it is a copied example. i have an xml file that i need to parse out an attribute for. i got that part figured out but my issue is that that attribute does not always exist in the xml file. here is my code:

#!/usr/bin/python
#import library to do http requests:
import urllib2
import os

#import easy to use xml parser called minidom:
from xml.dom.minidom import parseString

#download the history:
history = urllib2.urlopen('http://192.168.1.1/example.xml')
#convert to string:
historydata = history.read()
history.close()

#parse the xml you downloaded
dom = parseString(historydata)
xmlTagHistory = dom.getElementsByTagName('loaded')[0].toxml()
xmlDataHistory=xmlTagHistory.replace('<loaded>','').replace('</loaded>','')

print xmlDataHistory

when the attribute doesnt exist i get a return of "IndexError: list index out of range". what i am attempting to do with this code is to get it to run a command if the attribute doesnt exist, or it is false. the other issue i will probably have is that there will be times when that attribute appears more than once so i would also need it to account for that scenario by NOT running the command if there is even one instance of "loaded" being true. as i said, i am really new at this so i could use all the help i can get. much appreciated.

1
  • You are parsing out loaded which is an "element". In XML documents, the word "attribute" refers to the kind of thing that href is, as in <a href="http://example.com/">Example</a>. Commented Aug 26, 2012 at 17:56

2 Answers 2

2

Since dom.getElementsByTagName('loaded') returns a list, you can just check the list size with the len(list) function. Only if the list length is above 0, is it valid to do the [0] dereferencing.

An alternative is to wrap the code in try/exception pair and catch the parse exception.

Sign up to request clarification or add additional context in comments.

Comments

1

http://docs.python.org/tutorial/errors.html

using the try and except you should be able to handle everything you need.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.