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.

Answers


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[0]
    ET.SubElement(drug, 'Dose').text = row[1]
    ET.SubElement(drug, 'Unit').text = row[2]

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.


Need Your Help

jquery scroll to top convert to scroll to bottom

jquery scroll

I copied this code from the internet and wanted the get a identical result, however I want it to scroll down insted. I have tried to convert it as best I could, but I could not get it to work your ...

How to limit number of connections to a database in spring?

java spring

I have a Spring based application, deployed on the Tomcat server. What I need is to limit the maximum number of simultaneous connections to a database. This is data source section from my

Composer and multiple branches

php composer-php

I have a git project with 2 branches: