Santos
Santos

Reputation: 195

Modify mule XML file with python 3

Im working on a simple automation python3 script to modify some of my xml file on a mule4 projects, and based on input I want to add global elements, I found some cool things to do by using element tree, but im having a blocker where I cannot add multiple attributes, as a sample, I have:

<mule>
  some_code
</mule>

and I want to add this element as a new child element inside the tag 'mule':

<mule>
some_code
<http:listener-config name="HTTPS_Listener_config" doc:name="HTTP Listener config" doc:description="Secure HTTPS listener global config">
    <http:listener-connection protocol="HTTPS" host="${https.host}" port="${https.port}" tlsContext="TLS_Context" />
</http:listener-config>
</mule>

So.. I don't have much actual code beside the one I have been testing/playing with:

import xml.etree.ElementTree as ET

doc = ET.parse("./src/main/mule/global.xml")

root_node = doc.getroot()

child = ET.SubElement(root_node, "http:listener-config")

child.set("name","HTTPS_Listener_config")

connection  = ET.SubElement(child,"http:listener-connection")

connection.text =  "protocol=HTTPS"

tree = ET.ElementTree(root_node)

tree.write("./src/main/mule/global.xml")

This is the result... not quite there yet... plus thar 'ns#:' on the tags..

...
<http:listener-config name="HTTPS_Listener_config"><http:listener-connection>protocol=HTTPS</http:listener-connection></http:listener-config></ns0:mule>

any pointers on simple example will help me a lot, thanks!

Upvotes: 0

Views: 53

Answers (1)

aled
aled

Reputation: 25699

Probably to use python XML functions you need to set all the right namespace configurations right.

Though it is more error prone you might want to just replace text. For example replacing the end tag </mule> by a multi line string. Something like this:

f = open(filein,'r')
filedata = f.read()
f.close()

myconfig="""   <http:listener-config name="HTTPS_Listener_config" doc:name="HTTP Listener config" doc:description="Secure HTTPS listener global config">
    <http:listener-connection protocol="HTTPS" host="${https.host}" port="${https.port}" tlsContext="TLS_Context" />
</http:listener-config>
</mule>
"""
newdata = filedata.replace("</mule>",myconfig)

f = open(fileout,'w')
f.write(newdata)
f.close()

Upvotes: 1

Related Questions