I need to check whether a certain tag exists in an xml file.
For example, I want to see if the tag exists in this snippet:
If your document tends to be relatively short you can iterate over all children of looking for tags matching your set of variable names:
tree = lxml.etree.fromstring(DATA)
NAMES = set(['elem1', 'elem3'])
for node in tree.iterchildren():
if node.tag in NAMES:
print 'found', node.tag
Or you can search for each variable name one at a time:
for tag in ('elem1', 'elem3'):
if tree.find(tag) is not None:
print 'found', tag