user10783243
user10783243

Reputation: 59

Add new child with lxml.etree

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))

Upvotes: 2

Views: 2189

Answers (1)

Simon Crane
Simon Crane

Reputation: 2182

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))

Upvotes: 1

Related Questions