![](/img/trans.png)
[英]I keep getting the error: AttributeError: 'NoneType' object has no attribute '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.text
為None
的任何元素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.