I asked a question about adding multiple elements a couple weeks ago and now I’ve run into a similar issue. I have to create some XML where I’ll have the following:
<embossed>
<line>Test Line</line>
<line>Test Line 2</line>
<line>Test Line 3</line>
</embossed>
I cannot figure out how to create the same element N times in a row with different text using the LXML objectify.Element() method. I tried this:
embossed = objectify.Element('embossed')
embossed.line = objectify.Element("line")
embossed.line = objectify.Element("line")
But I end up with only one “line” element inside the “embossed” element. Does anyone know how to do this? Thanks!
Just append the lines to
embossed, instead:Each lxml tree tag acts like a list, where any children are elements in the list. Simply appending new
objectify.Elementobjects makes them children of the tag you append them to.You can then reach each element of that list by using indexing; the
-1index is the last element, allowing us to set it’s text.The above code outputs: