如何解决使用python 3
我正在研究一个简单的自动化python3脚本,以修改我在mule4项目上的一些xml文件,并根据输入要添加全局元素,发现使用元素树可以做一些很酷的事情,但是我有一个我无法添加多个属性的阻止程序,例如,我有:
<mule>
some_code
</mule>
,我想将此元素添加为标签“ 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>
所以..除了我一直在测试/玩过的代码之外,我没有太多实际的代码:
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")
这是结果...尚未完全实现...在标签上加上thar'ns#:'。
...
<http:listener-config name="HTTPS_Listener_config"><http:listener-connection>protocol=HTTPS</http:listener-connection></http:listener-config></ns0:mule>
任何简单示例的指针都会对我有很大帮助,谢谢!
解决方法
可能要使用python XML函数,您需要正确设置所有正确的名称空间配置。
尽管更容易出错,但您可能只想replace text。例如,用多行字符串替换结束标签</mule>
。像这样:
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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。