Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #44494

Re: xml.etree.ElementTree if element does not exist?

Subject Re: xml.etree.ElementTree if element does not exist?
From Stefan Holdermans <stefan@vectorfabrics.com>
Date 2013-04-29 13:22 +0200
References <CAM6w3non8j1FdKWwENH1GabCE4n-9muDfQKQURsLn9JLFGWtAw@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.1150.1367234562.3114.python-list@python.org> (permalink)

Show all headers | View raw


Ombongi,

> 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'
> 
> 
> some messages i receive will have the sepid parameter, other will not have this parameter. How can i cater for this? kinda like an if .. else implementation for xml.etree.ElementTree  ?

What about simply testing whether the value returned by find is None? For example:

  $ cat test.py
  from xml.etree import ElementTree

  myTree = ElementTree.fromstring('<test />')
  myElement = myTree.find('orange')

  if myElement is None:
      print 'tree does not contain a child element "orange"'
  else:
      print myElement.text
    

  $ python test.py
  tree does not contain a child element "orange"

HTH,

  Stefan

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: xml.etree.ElementTree if element does not exist? Stefan Holdermans <stefan@vectorfabrics.com> - 2013-04-29 13:22 +0200

csiph-web