Add new child with lxml.etree

Question:

this is my xml, i want to append to it some tags, i can write first subelement, but can’t write child in this new subelement.
Subelement that i created is called ‘movie’, i need to create another tag inside that tag

    <titlovi>
      <login>
        <token></token>
        <userid></userid>
      </login>
      <boris>
        <movies>
          <movie title="Avengers: Endgame"/>
        </movies>
        <tv_shows/>
      </boris>
    </titlovi>

Code:

    parser = etree.XMLParser(remove_blank_text=True)
    titlovi = etree.parse('titlovi.xml', parser).getroot()
    b = etree.SubElement(titlovi[1][0], 'movie').set('title', title)
    c = etree.SubElement(b, 'imdb_id').text = imdb_id
    with open('titlovi.xml', 'wb') as file:
        file.write(etree.tostring(titlovi, pretty_print=True))
Asked By: user10783243

||

Answers:

Separate the creation of subelements from the setting of their attributes:

parser = etree.XMLParser(remove_blank_text=True)
titlovi = etree.parse('titlovi.xml', parser).getroot()
b = etree.SubElement(titlovi[1][0], 'movie')
b.set('title', title)
c = etree.SubElement(b, 'imdb_id')
c.text = imdb_id
with open('titlovi.xml', 'wb') as file:
    file.write(etree.tostring(titlovi, pretty_print=True))
Answered By: Simon Crane
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.