Home > Software engineering >  How to rewrite XML file in gitlab from python
How to rewrite XML file in gitlab from python

Time:03-30

I read XML file from gitlab into a variable, then I do some manipulations with it. And I need to rewrite the file in gitlab using that variable. When I use dump - it deletes all from the file. How can I rewrite XML file in gitlab from python?

import gitlab
import io
import xml.etree.ElementTree as ET

gl = gitlab.Gitlab(
                private_token='xxxxx')
gl.auth()

projects = gl.projects.list(owned=True, search='Python')
raw_content = projects[0].files.raw(file_path='9_XML/XML_hw.xml', ref='main')
f = io.BytesIO()
f.write(raw_content)
f.seek(0)
xml_file = ET.parse(f)  # read file 

..... some manipulations with xml_file


project_id = 111111
project = gl.projects.get(project_id)
f = project.files.get(file_path='9_XML/XML_hw.xml', ref='main')
f.content = ET.dump(xml_file) # IT doesn't rewrite, it deletes everything from the file
f.save(branch='main', commit_message='Update file')

CodePudding user response:

ET.dump doesn't produce a return value. It only prints to stdout. As stated in the docs:

Writes an element tree or element structure to sys.stdout. This function should be used for debugging only.

Hence, you end up setting f.content = None.

Instead of using .dump, use .tostring:

xml_str = ET.tostring(xml_file, encoding='unicode')
f.content = xml_str
  • Related