Unknown
Unknown

Reputation: 13

Coding an XML document with python?

I am currently taking part in a Cyber Challenge, however I have beeen asked to produce an xml file which contains nodes and atributes:

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 looked everywhere for information on this and I cam up with the following. However, after submitting this code I get the following:

import xml.etree.cElementTree as ET

root = ET.Element("root")
ET.SubElement(root, "Country")
ET.SubElement(root, "Country")
ET.SubElement(root, "Panama")
tree = ET.ElementTree(root)
tree.write("/tmp/vulnerable-countries.xml")

Format of /tmp/vulnerable-countries.xml was not correct. It should contain 3 country nodes with name attributes, with the third being Panama.

Can anyone help?

Upvotes: 0

Views: 2062

Answers (1)

Robᵩ
Robᵩ

Reputation: 168876

The error message indicates that you need to include an attribute called name for each of your country nodes. Try this:

import xml.etree.cElementTree as ET

root = ET.Element("root")
ET.SubElement(root, "country", name="Narnia")
ET.SubElement(root, "country", name="Wakanda")
ET.SubElement(root, "country", name="Panama")
tree = ET.ElementTree(root)
tree.write("/tmp/vulnerable-countries.xml")

Result:

<root><country name="Narnia" /><country name="Wakanda" /><country name="Panama" /></root>

Upvotes: 2

Related Questions