【问题标题】:Modify mule XML file with python 3用 python 3 修改 mule XML 文件
【发布时间】:2020-11-04 23:44:20
【问题描述】:

我正在编写一个简单的自动化 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")

这是结果...还没有...加上标签上的'ns#:'..

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

任何关于简单示例的指针都会对我有很大帮助,谢谢!

【问题讨论】:

    标签: python-3.x xml mule


    【解决方案1】:

    可能要使用 python XML 函数,您需要正确设置所有正确的命名空间配置。

    虽然它更容易出错,但您可能只想replace text。例如用多行字符串替换结束标记&lt;/mule&gt;。像这样的:

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多