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

How can I implement header view + sliding pager tab strip + view pager like Fancy app?

android android-viewpager android-view

I'm curious how Fancy(https://play.google.com/store/apps/details?id=com.thefancy.app) implements this kind of view. Images at the below are captured on seller page of Fancy app.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.