How can I force python to ignore IndexError without using try & except every single value that I am extracting?
My XML have multiple values that needed to be extracted. Some records don’t have the value / at root[0], so I have to manually use try & except IndexError: for every single node that I am extracting.
Here’s my code:
try:
a = etree.XPath('/Data/a/b/nodeA/text()')(root)[0]
except IndexError:
a = ''
try:
b = etree.XPath('/Data/a/b/x/y/nodeB/text()')(root)[0]
except IndexError:
b = ''
try:
c = etree.XPath('/Data/a/b/d/nodeB/text()')(root)[0]
except IndexError:
c = ''
When I use xpath queries I try to use looping instead of indexing. That way if the query doesn’t find anything, the code nested in the loop never runs and you don’
t have to index because the loop values get bound to a local name in each iteration. Permit an example.