-1

I am using ixml to parse the XML doxument.

from lxml import etree
root=etree.XML(full xml tag file content)
 if (next(root.iterfind(".//one_inner_tag")).text is None):
      Print "NONE VALUE"
 else:
      Print root.iterfind(".//one_inner_tag")).text

While executing this code, I have faced an error like

if (next(root.iterfind(".//one_inner_tag")).text is None):
StopIteration

Because of the file content does not have that specific tag. If the Tag does not have a value means I need to print the NONE VALUE. But it prints the error.

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
sara
  • 115
  • 1
  • 2
  • 15
  • You could check the length of the iterable returned from iterfind, instead of calling next and comapring to None – M4rtini Jan 11 '16 at 14:04
  • This code is wasteful - you're doing the `iterfind` twice: once to determine if the element exists, and then another time to actually extract the text. – Corley Brigman Jan 11 '16 at 14:24
  • 1
    @CorleyBrigman: It's actually broken, not just wasteful. No iteration was done in the second use, so it's trying to get `.text` on the generator itself, which wouldn't work. In addition, it's got the wrong `print` capitalization (and if it's Py3 or Py2 with the `__future__` `print_function` import, it needs parens around the arguments to `print` to boot). – ShadowRanger Jan 11 '16 at 15:59
  • Possible duplicate of [How can I get a Python generator to return None rather than StopIteration?](http://stackoverflow.com/questions/7102050/how-can-i-get-a-python-generator-to-return-none-rather-than-stopiteration) – ShadowRanger Jan 11 '16 at 16:00

1 Answers1

2

next can take a second argument that is returned on exhaustion of the iterator, so try:

elem = next(root.iterfind(".//one_inner_tag"), None)  # Returns None on empty iterator
if elem is None or elem.text is None:
    print "NONE VALUE"
else:
    print elem.text
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271