R
R
Roman Shavukhin2020-10-22 14:35:12
Python
Roman Shavukhin, 2020-10-22 14:35:12

How to add a sub-element to xml without changing the rest of the elements?

Here is my code:

import xml.etree.ElementTree as ET
def ban(u_id, reason = None):
  xml_doc = ET.Element('root')
  u_id = str(u_id)
  #id
  user = ET.SubElement(xml_doc, 'user', id = u_id)
  #name
  ET.SubElement(user, 'name').text ="name"
  #reason
  ET.SubElement(user, 'reason').text = reason
  #date
  ET.SubElement(user, 'date').text = 'date_of_ban'
  tt = ET.ElementTree(xml_doc)
  #decoration
  prettify(xml_doc)
  #writing                   
  tt.write('banned.xml', encoding = 'UTF-8', xml_declaration = True)


After executing the function, my xml is overwritten, that is, the remaining subelements are deleted, but the created one remains

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question