繁体   English   中英

获取 AttributeError: 'NoneType' object 在读取 XML 时没有属性 'strip'

[英]Getting AttributeError: 'NoneType' object has no attribute 'strip' while reading XML

我正在阅读 XML 并在字典中添加 xml 内容但得到 AttributeError: 'NoneType' object 只要有空标签就没有属性'strip'。

a.xml

<?xml version="1.0"?>
<?xml-stylesheet href="population.xsl" type="text/xsl"?>
<!DOCTYPE catalog SYSTEM "catalog.dtd">
<population>
   <human description="male" product_image="male.jpg">
      <gender sex="Men">
         <id_number>RRX9856</id_number>
         <weight></weight>
      </gender>     
   </human>
</population>

代码:每当此代码运行时,它都会抛出提到的属性错误,因为有空标签,即 x.text() 为无。

from lxml import etree
from collections import defaultdict

root_1 = etree.parse('a.xml').getroot()

d1 = []
for node in root_1.findall('.//human '):
    item = defaultdict(list)
    for x in node.iter():
        if x.attrib:
            item[x.attrib.keys()[0]].append(x.attrib.values()[0])
        if x.text.strip():
            item[x.tag].append(x.text.strip())
    d1.append(dict(item))



d1 = sorted(d1, key = lambda x: x['gender'])
print(d1)

我试过的解决方案:

我正在阅读 XML 上方的内容,并使用以下代码将标签之间的空值替换为 None 并将其保存到一些不同的 b.xml。 但这是双重工作,我正在阅读原始 a.xml 然后用字符串 None 替换空值,然后将其保存到 b.xml 然后读取新的 Z0F635D0E0F3874FFF8B581C132EC6 文件。

"%s" % x.text()

是否有任何其他解决方案可以仅在原始 XML 中处理此错误,并且在阅读此 XML 时不会有任何问题,并且包括空值在内的所有元素也可以在结果中获取?

如果您只想忽略x.textNone的任何元素x ,则更改该行

        if x.text.strip():

        if x.text and x.text.strip():

但是,如果您希望包含None元素但不包含空元素(我不知道您为什么想要这个),那么替换这些行可能是最简单的

        if x.text.strip():
            item[x.tag].append(x.text.strip())

        if x is None:
            item[x.tag].append(None)
        elif x.text.strip():
            item[x.tag].append(x.text.strip())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM