Add multiple of same xml subelements to existing parent element

597 Views Asked by At

I'm trying to take a comma seperated list [Action, Adventure, Family] and for each item in the list, create a new tag inside of a tag.

The desired output:

<genres>
   <genre>Action</genre>
   <genre>Adventure</genre>
   <genre>Family</genre>
</genres>

My existing code that failes to work is as follows:

root = objectify.fromstring(xml)   # genres is an object at this point
.
.
.
for g in self.s.cell(self.r,self.d['Genre']).value.split() :
   root.product.genres.genre = g.rsplit(",")
.
.
.

Note: all the above for loop is doing is overwriting a single tag and resulting in the following:

<genres>
   <genre>Family</genre>    # last member of the list
</genres>

I have also tried the following and it did not work either:

for g in self.s.cell(self.r,self.d['Genre']).value.split() :
   genre = objectify.fromstring('<genre />')
   genre = g.rstrip(",")
   root.product.genres.append(genre)

Thanks in advance for your assistance.

2

There are 2 best solutions below

0
On

For same tags, lxml will store them in a list. Try this:

root = objectify.fromstring(xml)   # genres is an object at this point

n = 0

for g in self.s.cell(self.r,self.d['Genre']).value.split() :
   root.product.genres.genre[n] = g.rsplit(",")
   n += 1
0
On

Thanks for your response. I figured out a different way to do it:

for g in self.s.cell(self.r,self.d['Genre']).value.split() :
    genre = et.Element("genre")
    genre.text = g.rstrip(",")
    root.product.genres.append(genre)