Upload a modified XML file to google cloud storage after editting it with ElementTree (python)

Question:

I’ve modified a piece of code for merging two or more xml files into one. I got it working locally without using or storing files on google cloud storage.

I’d like to use it via cloud functions, which seems to work mostly fine, apart from uploading the final xml file to google cloud storage.

import os
import wget
import logging

from io import BytesIO
from google.cloud import storage
from xml.etree import ElementTree as ET

def merge(event, context):
    client = storage.Client()
    bucket = client.get_bucket('mybucket')
    test1 = bucket.blob("xml-file1.xml")
    inputxml1 = test1.download_as_string()
    root1 = ET.fromstring(inputxml1)
    test2 = bucket.blob("xml-file2.xml")
    inputxml2 = test2.download_as_string()
    root2 = ET.fromstring(inputxml2)
    copy_files = [e for e in root1.findall('./SHOPITEM')]
    src_files = set([e.find('./SHOPITEM') for e in copy_files])
    copy_files.extend([e for e in root2.findall('./SHOPITEM') if e.find('./CODE').text not in src_files])
    files = ET.Element('SHOP')
    files.extend(copy_files)
    blob = bucket.blob("test.xml")
    blob.upload_from_string(files)

Ive tried the functions .write and .tostring but unsuccessfully.

Asked By: Michal Fridrich

||

Answers:

Sorry for the incomplete question. I’ve already found a solution and I cant recall the error message I got.
Here is my solution:

blob.upload_from_string(ET.tostring(files, encoding='UTF-8',xml_declaration=True, method='xml').decode('UTF-8'),content_type='application/xml')
Answered By: Michal Fridrich