[python]Insert a xml block to an existing base xml document

Took me a while to understand how this Element Tree works.. I have a specific requirement to insert a block of xml into a base xml document, this document will then be encoded in utf-8 and send to the API server.

import xml.etree.ElementTree as ET

from copy import copy

access_request = []
with open("config.xml", "r") as file:
    base = file.read()

body = ET.fromstring(base)

ar_field = body.find('.//field')

ar = ET.Element('access_request')
ET.SubElement(ar, 'sources')
ET.SubElement(ar, 'destinations')
ET.SubElement(ar, 'services')
ET.SubElement(ar, 'action')

for i in range(0, 3):

for ar_tag in access_request:

print(ET.tostring(body, encoding='utf-8').decode('utf-8'))

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s