【问题标题】:Getting AttributeError: 'NoneType' object has no attribute 'strip' while reading XML获取 AttributeError:“NoneType”对象在读取 XML 时没有属性“strip”
【发布时间】:2020-06-21 18:04:07
【问题描述】:

我正在读取 XML 并在字典中添加 xml 内容,但出现 AttributeError: 'NoneType' object has no attribute '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,然后读取新的 xml 文件。

"%s" % x.text()

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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    如果您只想忽略xx.textNone 的任何元素,请更改行

            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())
    

    【讨论】:

    • 我试过了,但忽略不是解决方案。我还必须从 XML 打印所有 None 元素
    • @Enigmaderockz:您目前正在忽略带有空(或仅空白)文本的元素,但您想包含文本为 None 的元素?不知道你为什么要这样做,但处理这种情况很容易,所以我编辑了我的答案来说明如何做。
    猜你喜欢
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 2022-07-21
    相关资源
    最近更新 更多