简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM