Parse empty tag with ElementTree

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Parse empty tag with ElementTree



Trying to parse XML using ElementTree. I cannot figure out how to treat empty tags like <tag/>. If the tag is not present at all, .find() returns None and everything is fine. However with <tag>, .find() returns something and the consequent attempt to call text fails with error:


<tag/>


.find()


None


<tag>


.find()


text


TypeError: must be str, not NoneType



Failing example below. It will fail to parse the line <tl><mpa/></tl>


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




1 Answer
1



With an empty tag <mpa/>, your mpa variable is a valid node so it is not None, but mpa.text is None because there's no text inside. Your attempt to concatenate a string " |--> Tag Value: " to None therefore fails since concatenation only works on two strings. Instead, you can use the formatting operator to format None as 'None', and add a condition to the following line to avoid converting mpa.text to an integer if it is None:


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



With the above change the output becomes:


Item: 1
|--> Is None, assigned 0.
Item: 2
|--> Is Something
|--> Tag Value: 0010
Item: 3
|--> Is Something
|--> Tag Value: None






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Arduino Mega cannot recieve any sketches, stk500_recv() programmer is not responding

Visual Studio Code: How to configure includePath for better IntelliSense results

Future solutions