1

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.

2
  • 2
    Without seeing your assignment it's hard to be sure, but the phase "3 country nodes" makes me think your nodes should be country elements, like <country name="China"/>, <country name="Panama"/>, etc. Commented Apr 8, 2019 at 18:51
  • Read about Element Objects and what are attributes. Commented Apr 8, 2019 at 19:08

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.