[英]How to solve the StopIteration issue while the XML tag does not have a value using Python script
I am using ixml to parse the XML doxument. 我正在使用ixml来解析XML文档。
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.
但是它会打印错误。
next
can take a second argument that is returned on exhaustion of the iterator, so try: next
可以使用第二个参数,该参数在迭代器用尽时返回,因此请尝试:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.