Reputation: 167
I have been given a problem that consists of generating a xml file using python but in a slightly different manner. I think I am misunderstanding the question and if so an explanation in simple terms would help greatly. Here is the problem:
Generate a valid xml file at /tmp/vulnerable-countries.xml. It should contain a list of country nodes attached to a root node that have name attributes, the third node should be Panama.
I have attempted this problem many times but I am consistently getting the message :
Format of /tmp/vulnerable-countries.xml was not correct. It should contain 3 country nodes with name attributes, with the third being Panama.
Here is my code so far:
import xml.etree.cElementTree as ET
root = ET.Element("root")
ET.SubElement(root, "field1").set('Name','Blah')
ET.SubElement(root, "field2").set('Name','Complete')
ET.SubElement(root, "Panama").set('Name','Panama')
tree = ET.ElementTree(root)
tree.write("/tmp/vulnerable-countries.xml")
Clearly I am doing something wrong but I cannot figure it out. How do I actually solve the problem given to me.
Upvotes: 1
Views: 1274
Reputation: 23815
How about
import xml.etree.ElementTree as ET
root = ET.Element("root")
countries = ['USA', 'Brazil', 'Panama']
for country in countries:
ET.SubElement(root, 'country').set('name', country)
tree = ET.ElementTree(root)
tree.write('c:\\temp\\vulnerable-countries.xml')
Output
<root>
<country name="USA" />
<country name="Brazil" />
<country name="Panama" />
</root>
Upvotes: 2