My XML:
<animals>
<animal name="fox" fullname="fullfox"></animal>
<animal name="dog" fullname="halfdog"><food>milk</food><food>rice</food><food>meat</food> </animal>
<animal name="cow" fullname="doublecow"><food>grass</food></animal>
<animal name="blabla" fullname="fullbla"></animal>
</animals>
I'm trying to parse this XML to get same XML as output.
doc = ET.parse("an.xml")
root = doc.getroot() #Returns the root element for this tree.
root_new = ET.Element("animals")
for child in root:
name = child.attrib['name']
fullname = child.attrib['fullname']
for g in root.findall("*/food"):
animal = ET.SubElement(root_new, "animal")
food = ET.SubElement(animal, "food")
food.text = g.text
animal.set("name",name)
animal.set("fullname",fullname)
tree = ET.ElementTree(root_new)
tree.write(sys.stdout)
But am getting only last value
<animals>
<animal fullname="fullbla" name="blabla"><food>milk</food></animal>
<animal fullname="fullbla" name="blabla"><food>rice</food></animal>
<animal fullname="fullbla" name="blabla"><food>meat</food></animal>
<animal fullname="fullbla" name="blabla"><food>grass</food></animal>
</animals>
And food node also wrong, how to iterate exactly like my input XML?
foodtags that are children of an object. Try to iterate over the animals and for each animal iterate over the foods.