Python Lxml (objectify): Checking whether a tag exists

Biosci3c picture Biosci3c · Mar 22, 2011 · Viewed 19.3k times · Source

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:

 <main>
       <elem1/>
       <elem2>Hi</elem2>
       <elem3/>
       ...
 </main>

Currently, I am using an ugly hack with error checking, like this:

try:
   if root.elem1.tag:
      foo = elem1
except AttributeError:
   foo = "error finding elem1"

I also want to customize the string if it is unable to find the node (i.e. "unable to find -tagname-").

I have to check a long list of variables, and I don't want to repeat the code 100 times.

Any suggestions?

Edit:

Here is a snip of the actual xml file:

<main>
 <asset name="Virtual Dvaered Unpresence">
  <virtual/>
  <presence>
   <faction>Dvaered</faction>
   <value>-1000.000000</value>
   <range>0</range>
  </presence>
 </asset>
 <asset name="Virtual Empire Small">
  <virtual/>
  <presence>
   <faction>Empire</faction>
   <value>100.000000</value>
   <range>2</range>
  </presence>
 </asset>
</main>

I want to check whether the tag exists, and, if so, to get the contents.

Edit edit: Ok, I am going to combine two of the answers, but I can only vote for one. Sorry.

Edit 3: Related question about XPath here: Python lxml (objectify): Xpath troubles

Answer

Sleep_Walker picture Sleep_Walker · Jan 9, 2012

hasattr() works for this:

if hasattr(root, 'elem1'):
    foo = root.elem1