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.

4

2 回答 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.

于 2012-08-26T17:42:40.957 回答
1

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

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

于 2012-08-26T17:44:52.030 回答