Reputation: 305
Basically I need to loop through a python dict and create an xml element tag with the for loop returned values as xml element keys, I.e:
d = {}
d["a"] = "1"
d["b"] = "2"
d["c"] = "what"
root = ET.Element("root")
child = ET.SubElement(root, "child")
for k,v in d.items():
ET.SubElement(child, "field1", k=v).text = "some value1"
tree = ET.ElementTree(root)
tree.write("logs/filename.xml")
I want the result to look like:
<root><child><field1 a="1" b="2" c="what">some value1</field1></child></root>
Upvotes: 1
Views: 356
Reputation: 40773
You only add field1 once:
d = dict(a="1", b="2", c="what")
root = ET.Element("root")
child = ET.SubElement(root, "child")
field1 = ET.SubElement(child, "field1")
field1.attrib.update(d)
field1.text = "some value1"
Upvotes: 1