简体   繁体   English

使用Python脚本在XML标签没有值的情况下如何解决StopIteration问题

[英]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.

相关问题 如何解决 Python 中的 StopIteration 错误? - How to solve StopIteration error in Python? 使用python提取与xml标记关联的值时出现问题 - Issue in extracting value associated with xml tag using python 如何使用ElementTree在xml文件中搜索标签,其中我有一个具有特定值的特定“父”标签? (蟒蛇) - How do I search for a Tag in xml file using ElementTree where i have a certain “Parent”tag with a specific value? (python) 容器化 python 脚本因 StopIteration 失败 - Containerized python script fails with StopIteration “RuntimeError: generator raise StopIteration”如何解决这个python问题? - “RuntimeError: generator raised StopIteration” how to fix this python issue? 在解析 xml 时没有得到任何类型,即使它有一些价值,我该如何解决这个问题? - while parsing xml getting none type even it has some value,how can i solve this issue? 如果使用 xml.etree.ElementTree 有标签值,则 Python xml 读取 - Python xml read if have tag value using xml.etree.ElementTree 如何使用python在xml中的特定标签elemnet中查找值? - How to find the value in particular tag elemnet in xml using python? 如何使用 python 提取 xml 中的单个特定标签值并修改 - How to extract single particular tag value in xml using python and modify 如何使用python搜索和替换xml中的标签和属性值 - How to search and replace tag and attribute value in xml using python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM