使用python

时间:2017-09-08 09:03:54

标签: python xml

我正在尝试替换此xml中的值,我要替换的是所有出现的ip 10.10.10.75。

    <profile name="internal">
    <settings>
     <param name="rtp-ip" value="10.10.10.75"/>
        <!-- ip address to bind to, DO NOT USE HOSTNAMES ONLY IP ADDRESSES -->
        <param name="sip-ip" value="10.10.10.75"/>
    <param name="presence-hosts" value="10.10.10.75,10.10.10.75"/>

 </settings>
</profile>

这是我的示例代码

#!/usr/bin/python

from shutil import copyfile
import xml.etree.ElementTree as ET
#try:

#       copyfile('/usr/src/sample.xml','/usr/src/sample3.xml')
#       print "Profile Copied Sucessfully"

#except IOError as e:
#    print "I/O error({0}): {1}".format(e.errno, e.strerror)

with open('/usr/src/sample3.xml') as f:
  tree = ET.parse(f)
  root = tree.getroot()

  for elem in root.getiterator():
    try:
      elem.text = elem.text.replace('10.10.10.75', '10.10.10.100')
    #  elem.text = elem.text.replace('FEATURE NUMBER', '123456')
    except AttributeError:
      pass

tree.write('/usr/src/sample3.xml')

这没有得到我想要的东西,它也删除了我不想做的评论行。

2 个答案:

答案 0 :(得分:0)

这应该可以解决问题:

from lxml import etree
import os

xml_file = "/usr/src/sample.xml"
xml_file_output = '{}_out.xml'.format(os.path.splitext(xml_file)[0])

parser = etree.XMLParser(remove_comments=False)
tree = etree.parse(xml_file, parser)
root = tree.getroot()

for param in root.iter("param"):
    replaced_ip = param.get("value").replace("10.10.10.75", "10.10.10.100")
    param.set("value", replaced_ip)

tree.write(xml_file_output)

修改

我配置了解析器,因此不会删除注释。

答案 1 :(得分:0)

如果您想要替换事件,为什么不将它视为字符串?

with open('/usr/src/sample3.xml') as f:
    xml_str = f.read()
xml_str = xml_str.replace('10.10.10.75', '10.10.10.100')

with open('/usr/src/sample3.xml', "w") as f:
    f.write(xml_str)