[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):
    access_request.append(copy(ar))

for ar_tag in access_request:
    ar_field.append(ar_tag)

print(ET.tostring(body, encoding='utf-8').decode('utf-8'))
Advertisements
This entry was posted in Python, Scripting and tagged , , , . Bookmark the permalink.

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 )

Google+ photo

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

Twitter picture

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

Facebook photo

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

w

Connecting to %s