2017-09-08 29 views
-1

我試圖替換這個xml中的值,我想要替換的是這個ip 10.10.10.75所有匹配項。使用python查找xml文件中的替換

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

這沒有得到我想要的東西,它的去除註釋行也,我不想做的事。

回答

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

編輯

這樣的評論不會被刪除我配置解析器。