2

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 Answers 2

0

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
0

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.