I am writing a python script to find various tags in an XML file, and want to have warnings if a particular tag can't be found (indicating our metadata is incomplete). This works fine for an element for which there is only one instance:
try:
element = tree.find("idinfo/descript/abstract")
if element is None:
print "(!) No description/abstract in file"
print "ABSTRACT: {}".format(element.text)
except:
print "(!) No description/abstract found"
This loop works for finding all procdate
elements, but doesn't give any error message when there are none, either the "if None" or "except" warning versions.
try:
for element in tree.findall("dataqual/lineage/procstep/procdate"):
if element is None:
print "(!) No revision date in file"
print "REVISION DATE: {}".format(element.text)
except:
print "(!) No revision date found"
[If I can't actively flag something as empty, that's not a big deal, but it would be nice to be able to alert the user...]
When nothing is found,
findall()
returns an empty list. Test for that first:not results
suffices, as empty containers test as false in a boolean context.