先上代码:
1 #!/usr/bin/env python3 2 # _*_ coding: utf-8 _*_ 3 from xml.dom.minidom import Document 6 7 def readFile(filename, lines): 8 with open(filename, \'r\') as f: 9 for line in f: 10 line = line.rstrip(\' \n\') 11 if line.startswith(\'//\') or len(line) == 0: 12 continue 13 lines.append(line) 14 15 def writeXml(filename, lines, tagNames): 16 # 创建doc 17 doc = Document() 18 # 创建根节点 19 root = doc.createElement(tagNames[0]) 20 doc.appendChild(root) 21 22 # 记录每层节点的最新元素 23 nodes = {0: root} 24 25 for line in lines: 26 index = line.rfind(\' \') 27 level = (index + 1) / 4 + 1 28 line = line.lstrip(\' \') 29 30 node = doc.createElement(tagNames[level]) 31 node.setAttribute(\'name\', line) 32 33 nodes[level - 1].appendChild(node) 34 nodes[level] = node 35 36 with open(filename, \'w\') as f: 37 f.write(doc.toprettyxml(indent=\'\t\')) 38 39 def display(lines): 40 for line in lines: 41 print(line) 42 43 if __name__ == \'__main__\': 44 lines = [] 45 readFile(\'./file/sector.txt\', lines) 46 47 tagNames = [\'SectorFile\', \'Sectors\', \'sector\', \'sector_second\'] 48 writeXml(\'./file/sector.xml\', lines, tagNames)
1. 使用库 xml.dom.minidom
2. readFile函数
这个函数的功能上读取文件,并把每一行内容除去右边空格,存入列表中
参数一:文件名
参数二:文件行存入的列表
3. writeXml函数
功能:读取列表,生成xml文件
参数一:生成的xml文件名
参数二:文件行列表
参数三:xml标签名
此处读取的文件,左侧是通过tab键进行分层的。但由于编辑器设置的一个tab键,替换成四个空格。所以此处的规律是查找最后一个空格出现的位置,加1除4就可以得到该文件在xml中所处的层级。
第22行:此处的目的是建立一个level-node的字典,用于存放当前层级的最新节点。便于字节点查找父节点