使用 ElementTree 解析空标签
Parse empty tag with ElementTree
正在尝试使用 ElementTree 解析 XML。我不知道如何处理像 <tag/>
这样的空标签。如果标签根本不存在,.find()
returns None
一切都很好。然而,对于 <tag\>
、.find()
returns 某些东西以及随后调用 text
的尝试失败并出现错误:
TypeError: must be str, not NoneType
下面是失败的例子。它将无法解析行 <tl><mpa/></tl>
from xml.etree import ElementTree
def getStuff(xml_message):
message_tree = ElementTree.fromstring(xml_message)
ns = {'a': 'http://www.example.org/a',
'b': 'http://www.example.org/b'}
tls = message_tree.findall('.//b:tl', namespaces = ns)
result, i = (0,)*2
for tl in tls:
i += 1
print("Item: " + str(i))
mpa = tl.find("b:mpa", namespaces = ns)
if mpa is None:
result = result + 0
print(" |--> Is None, assigned 0.")
else:
print(" |--> Is Something")
# This is where things go terribly wrong
print(" |--> Tag Value: " + mpa.text)
result = result + int(mpa.text)
return result
instr = """<?xml version="1.0" standalone='no'?>
<ncr xmlns="http://www.example.org/a">
<x xmlns="http://www.example.org/b">
<tl><ec code="N">e1</ec></tl>
<tl><mpa>0010</mpa></tl>
<tl><mpa/></tl>
</x>
</ncr>
"""
getStuff(instr)
对于空标签 <mpa/>
,您的 mpa
变量是一个有效节点,因此它不是 None
,但 mpa.text
是 None
,因为有里面没有文字。因此,您尝试将字符串 " |--> Tag Value: "
连接到 None
失败,因为连接仅适用于两个字符串。相反,您可以使用格式化运算符将 None
格式化为 'None'
,并向以下行添加条件以避免将 mpa.text
转换为整数,如果它是 None
:
print(" |--> Tag Value: %s" % mpa.text)
if mpa.text is not None:
result = result + int(mpa.text)
通过上述更改,输出变为:
Item: 1
|--> Is None, assigned 0.
Item: 2
|--> Is Something
|--> Tag Value: 0010
Item: 3
|--> Is Something
|--> Tag Value: None
正在尝试使用 ElementTree 解析 XML。我不知道如何处理像 <tag/>
这样的空标签。如果标签根本不存在,.find()
returns None
一切都很好。然而,对于 <tag\>
、.find()
returns 某些东西以及随后调用 text
的尝试失败并出现错误:
TypeError: must be str, not NoneType
下面是失败的例子。它将无法解析行 <tl><mpa/></tl>
from xml.etree import ElementTree
def getStuff(xml_message):
message_tree = ElementTree.fromstring(xml_message)
ns = {'a': 'http://www.example.org/a',
'b': 'http://www.example.org/b'}
tls = message_tree.findall('.//b:tl', namespaces = ns)
result, i = (0,)*2
for tl in tls:
i += 1
print("Item: " + str(i))
mpa = tl.find("b:mpa", namespaces = ns)
if mpa is None:
result = result + 0
print(" |--> Is None, assigned 0.")
else:
print(" |--> Is Something")
# This is where things go terribly wrong
print(" |--> Tag Value: " + mpa.text)
result = result + int(mpa.text)
return result
instr = """<?xml version="1.0" standalone='no'?>
<ncr xmlns="http://www.example.org/a">
<x xmlns="http://www.example.org/b">
<tl><ec code="N">e1</ec></tl>
<tl><mpa>0010</mpa></tl>
<tl><mpa/></tl>
</x>
</ncr>
"""
getStuff(instr)
对于空标签 <mpa/>
,您的 mpa
变量是一个有效节点,因此它不是 None
,但 mpa.text
是 None
,因为有里面没有文字。因此,您尝试将字符串 " |--> Tag Value: "
连接到 None
失败,因为连接仅适用于两个字符串。相反,您可以使用格式化运算符将 None
格式化为 'None'
,并向以下行添加条件以避免将 mpa.text
转换为整数,如果它是 None
:
print(" |--> Tag Value: %s" % mpa.text)
if mpa.text is not None:
result = result + int(mpa.text)
通过上述更改,输出变为:
Item: 1
|--> Is None, assigned 0.
Item: 2
|--> Is Something
|--> Tag Value: 0010
Item: 3
|--> Is Something
|--> Tag Value: None