xml操作

 1 import random
 2 import glob
 3 import xml.etree.ElementTree as ET
 4 
 5 def IdFactory(startNumber, taskTotal, expectNumberList , outputArrayLength, ouputArrayNumber ):
 6     for outputNumber in range(ouputArrayNumber):
 7         outputArray = []
 8         for outputLength in range(outputArrayLength):
 9             #产生不重复的随机数
10             while True:
11                 flag = False
12                 number = str(random.choice(range(startNumber,startNumber + taskTotal )))
13                 numberDeal = 'F' + number
14                 for expectNumber in expectNumberList:
15                     if numberDeal is expectNumber:
16                         flag = True
17                 if (outputArray.count(numberDeal) is 0) and (not flag):
18                     break
19             #存储
20             outputArray.append(numberDeal)
21         return outputArray
22 
23 def load_xml_file(fileName):
24     tree = ET.parse(fileName)
25     root = tree.getroot()
26     #获取所有objectgroup节点
27     all_objectgroups = root.findall('objectgroup')
28     #遍历list节点的子元素
29     for objectgroup in all_objectgroups:
30         if objectgroup.attrib['name'] == 'objects':
31             for anobject in objectgroup:
32                 for properties in anobject:
33                     for aproperty in properties:
34                         if aproperty.attrib['name'] == 'flags':
35                             expectNumberStr = aproperty.attrib['value']
36                             expectNumberList = expectNumberStr.split(',')
37                             IdArray = IdFactory(101,16,expectNumberList,6,1)
38                             c = ','.join(IdArray)
39                             aproperty.set('value',aproperty.attrib['value'] +',' + c )
40                             print aproperty.attrib['value']
41     tree.write('j:\\output\\' + fileName)
42 
43 
44 fileNames = glob.iglob(r"*.tmx")
45 print fileNames
46 for file in fileNames:
47     load_xml_file(file)

用来完成一个重复性的flag添加工作。

posted @ 2013-04-20 00:00  WINSTON-DEAN  阅读(121)  评论(0编辑  收藏  举报