Add sub-elements to newly created elements in python elementtree
I am trying to add the following subtree to an element 'Drugs' in an xml file using elementtree in Python based on the data in CSV file:
<Drug> <DrugID>1<DrugID> <Dose>40</Dose> <Unit>mg</Unit> </Drug> <Drug> <DrugID>3<DrugID> <Dose>1</Dose> <Unit>g</Unit> </Drug>
The thing is once I have created the Drug element, how do I reference it to use the append function? element.append() as I understand it needs element to be a direct reference to the parent. If I use .find() when adding the second drug, I may instead get a reference to the first drug.
I am cycling through each line of CSV while doing this so that's why I'd rather add element by element rather than appending a subtree to the element Drugs.
Use the SubElement factory to add new elements, it's much easier to use:
from xml.etree import ElementTree as ET # drugs is a reference to your <Drugs> element for row in csvreader: drug = ET.SubElement(drugs, 'Drug') ET.SubElement(drug, 'DrugID').text = row ET.SubElement(drug, 'Dose').text = row ET.SubElement(drug, 'Unit').text = row
where I assume that the columns 1 - 3 are the drug id, dose and unit, adjust as required for your CSV file.
Calling SubElement() creates the element, adds it to the parent and returns the newly created element for further processing.