xml.etree.ElementTree if element does not exist?

Neil Cerutti neilc at norwich.edu
Mon Apr 29 08:25:34 EDT 2013


On 2013-04-29, Ombongi Moraa Fe <moraa.lovetakes2 at gmail.com> wrote:
>
> Good Afternoon,
>
> Among other elements values that my script finds is value for sepid
>
> sepid = content.find(".//{http://www.huawei.com.cn/schema/common/v2_1}sepid
> ").text
>
>
> however, if i pass xml data that DOES NOT contain sepid element, i get an
> error:
>
> Traceback (most recent call last):
>   File "/usr/local/bin/receive.py", line 21, in <module>
>     sepid = content.find(".//{
> http://www.huawei.com.cn/schema/common/v2_1}sepid").text
> AttributeError: 'NoneType' object has no attribute 'text'

find returns None when it doesn't find what you asked for. So you
can't check the .text attribute right away unless you want an
exception thrown. I deal with these annoyances like this:

sepelem = content.find(".//{http://www.huawei.com.cn/schema/common/v2_1}sepid")
if sepelem is not None:
   sepid = sepid.text
else:
   sepid = ''

The empty string works for my purposes. Your script might need
something else.

-- 
Neil Cerutti



More information about the Python-list mailing list