python改XML
1 from lxml import etree 2 import os 3 4 5 # 查询文件夹中所有的xml文件,存到xml_files中 6 def findXmlFile(filePath): 7 xml_files =[] 8 for root, folder, files in os.walk(filePath): 9 for file in files: 10 if file.endswith('.xml'): 11 xml_files.append(os.path.join(root, file)) 12 return xml_files 13 14 15 16 #模糊匹配目录xml文件名,符合条件的文件存到target_file列表中 17 def fuzzyfinder(user_input, xml_files): 18 target_file =[] 19 for xml_file in xml_files: # 遍历文件夹中的文件,i:'d:\\xml\\LiveCheck_Provider_HttpRS1.xml' 20 if xml_file.find(user_input) > 0: 21 target_file.append(xml_file) 22 return target_file 23 24 25 #查找要替换的目标元素 26 def findByXpath(target_file,target_filed): 27 #循环查找遍历xml文件 28 ret = [] 29 elementName = [] 30 for path in target_file: 31 xml = etree.parse(path, etree.HTMLParser()) #利用lxml解析库的 etree.parse方法 32 target_filed_lower = target_filed.lower() # 转换为小写 33 command = '//@' + target_filed_lower # 目标字段转成://@rateplancode 34 result = xml.xpath(command) # 用xpath找到目标,结果是list,如有RatePlanCode="DSRPLO01",RatePlanCode="DSRPLO02",用//@rateplancode找到的值是:['DSRPLO01', 'DSRPLO02'] 35 fileName = "文件名:" + os.path.basename(path) # 获取文件名,如:文件名:LiveCheck_P1rovider_HttpRS.xml 36 print fileName 37 for i in range(len(result)): # 遍历xpath查到的结果 38 str = target_filed + '="' + result[i] + '"' # 把字段和结果拼接起来,RatePlanCode="DSRPLO01",RatePlanCode="DSRPLO02" 39 elementName.append(str) # 拼接结果放到列表 40 print(elementName) 41 ret.append(elementName) 42 elementName = [] 43 44 def my_Replace(content, target_filed, new_filed, index=0): 45 # 替换成修改的数据 46 print target_filed, new_filed, index 47 str = content.replace(target_filed, new_filed, int(index)) 48 # 把前面被替换的数据修改回来 49 a = int(index) - 1 50 ret = str.replace(new_filed, target_filed, a) 51 return ret 52 53 def writeXML(target_file,target_filed,new_filed,index): 54 # 替换内容并写入文件 55 for path in target_file: 56 with open(path, "r") as file: 57 fullcontent = file.read()#获取文件所有内容 58 if len(index) == 0: 59 content = fullcontent.replace(target_filed,new_filed) 60 else: 61 content = my_Replace(fullcontent,target_filed,new_filed,index) 62 f = open(path, 'w') 63 f.write(content) 64 f.close() 65 66 67 if __name__ == '__main__': 68 xml_files =[] 69 elementNames=[] 70 #遍历文件夹中xml的数量 71 xml_files = findXmlFile("D:/xml") 72 if len(xml_files): 73 print("文件夹中所有XML文件:") 74 print(xml_files) 75 user_input = raw_input("请输入需要修改的文件名(大小写敏感):") 76 target_file = fuzzyfinder(user_input,xml_files) 77 if len(target_file): 78 print("匹配到的XML文件:") 79 print target_file 80 target_filed = raw_input("输入需要查询的元素: ") 81 while(1): 82 findByXpath(target_file, target_filed) 83 old = raw_input("输入需要修改原内容:") 84 new = raw_input("输入需要修改后的内容:") 85 i = raw_input("输入需要修改的下标:") 86 if old == '': 87 break 88 else: 89 writeXML(target_file,old,new,i) 90 else: 91 print ("没有匹配到XML文件") 92 else: 93 print("文件夹中不存在XML文件:")
posted on 2020-03-08 22:35 fengyelan2233 阅读(218) 评论(0) 编辑 收藏 举报