首页 > 解决方案 > 使用python替换XML标签值

问题描述

我有一个 XML 文件,我需要在其中替换过滤器标记内的值。我试图解析这个 XML,但看起来有一些我无法解决的错误。任何人都可以帮我更换价值。

path = """
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
  <SOAP:Header>
    <header xmlns="xmlapi_1.0">
      <security>
        <user>testuser</user>
        <password hashed="false">testpassword</password>
      </security>
      <requestID>XML_API_client@n</requestID>
    </header>
  </SOAP:Header>
  <SOAP:Body>
    <find>
      <fullClassName>equipment.PhysicalPort</fullClassName>
      <filter>
        <equal name="siteId" value="x.x.x.x." />
      </filter>
      <resultFilter>
        <attribute>objectFullName</attribute>
        <attribute>displayedName</attribute>
        <attribute>portName</attribute>
        <attribute>description</attribute>
        <attribute>lagMembershipId</attribute>
        <attribute>encapType</attribute>
        <attribute>mode</attribute>
        <attribute>speed</attribute>
        <attribute>mtuValue</attribute>
      </resultFilter>
    </find>
    <find xmlns="xmlapi_1.0">
      <fullClassName>ethernetequipment.EthernetPortSpecifics</fullClassName>
    <filter>
      <equal name="siteId" value="x.x.x.x." />
    </filter>
    <resultFilter>
      <attribute>autoNegotiate</attribute>
      <attribute>downWhenLooped</attribute>
    </resultFilter>
  </find>
"""

我尝试的另一种方式:

path = '../request.xml'
IP = '"' + '63.130.111.89' + '"' + '/>'
f = open('test.xml', 'w+')
for line in open(path, 'r'):
    output_line = line
    string1, string2 = "siteId", "value"
    if string1 in output_line:
        value = output_line.split("value"'=', 1)[1]
        output_line = str.replace(output_line, value, IP)
f.write(output_line)

标签: python

解决方案


推荐阅读