Working with namespace while parsing XML using ElementTree



This is follow on question for Modify a XML using ElementTree


I am now having namespaces in my XML and tried understanding the answer at Parsing XML with namespace in Python ElementTree and have the following.


XML file.



<project xmlns="http://ift.tt/IH78KX" xmlns:xsi="http://ift.tt/ra1lAU" xsi:schemaLocation="http://ift.tt/IH78KX http://ift.tt/VE5zRx">
<grandParent>
<parent>
<child>Sam/Astronaut</child>
</parent>
</grandParent>
</project>


My python code after looking at Parsing XML with namespace in Python ElementTree



import xml.etree.ElementTree as ET

spaces='xmlns':'http://ift.tt/IH78KX','schemaLocation':'http://ift.tt/VE5zRx'}

tree = ET.parse("test.xml")
a=tree.find('parent')
for b in a.findall('child', namespaces=spaces):
if b.text.strip()=='Jay/Doctor':
print "child exists"
break
else:
ET.SubElement(a,'child').text="Jay/Doctor"

tree.write("test.xml")


I get the error: AttributeError: 'NoneType' object has no attribute 'findall'


No comments:

Post a Comment