1 #coding=utf-8 2 from xml.etree import ElementTree 3 4 import pdb 5 6 def printNodeInfo(node): 7 8 #node.tag 标签名称 9 #node.text 文本属性 10 print 'node.tag: %s' %node.tag 11 12 #node.attrib 属性字典 13 for key in node.attrib: 14 print '%s %s' %(key,node.attrib[key]) 15 return None 16 17 def main(): 18 19 pdb.set_trace() 20 try: 21 #ElementTree.parse(source,parser=None) 22 #将xml文件加载并返回ElementTree 对象 23 #parser 是一个可选的参数,如果为空则使用标准的XMLParser 24 #step 1: 获取 ElementTree 对象 25 xmlDoc = ElementTree.parse('D:\server\map\App.xml') 26 #step 2: 获取 根节点 27 root = xmlDoc.getroot() 28 #root.getchildren() 获取节点 返回的是列表 29 gateServerNodeList = root.getchildren() 30 31 # 下面是在每个gateServer 节点下 增加一个子节点 32 for node in gateServerNodeList: 33 # ElementTree.SubElement(parentNode,tagName) 34 #给parentNode 增加一个子节点 35 #和parentNode.append(Element) 效果一致 36 newNode = ElementTree.SubElement(node,'ActiveType') 37 # 设置属性 38 newNode.attrib['id'] = '9' 39 newNode.attrib['level'] = '38' 40 newNode.attrib['begin'] = '201401010000' 41 newNode.attrib['end'] = '201401010000' 42 #中文 需要 特殊译码 43 newNode.attrib['tip'] = '测试'.decode('utf-8') 44 #节点尾部的符号 45 newNode.tail = '\n' 46 #node.append(newNode) 47 48 # 写入文件 调用 之前的ElementTree 对象的 49 #write(fileName,encoding = None,xml_Decleare = None,default_namespace = None,method = None) 50 # 其中xml_Decleare 如果为 True 则 在 文档的最上方会写入 51 # 52 xmlDoc.write('D:test.xml','utf-8',True) 53 except Exception as e: 54 print e 55 56 return None 57 58 if __name__ == '__main__': 59 main()
1 from xml.etree import ElementTree as ET 2 3 tree = ET.parse('first.xml') 4 5 root = tree.getroot() 6 # print(root.tag) 7 # print(root.attrib) 8 # print(root.text) 9 # 创建节点,element类型 10 son = root.makeelement('tt',{'vv':'KK'}) 11 s = son.makeelement('tt',{'kk':'132443'}) 12 # son = ET.Element('tt',{'vv':'KK'}) 13 # s = ET.Element('tt',{'kk':'132443'}) 14 son.append(s) 15 root.append(son) 16 tree.write('out.xml')
简单创建xml
1 from xml.etree import ElementTree as ET 2 3 root = ET.Element('root',{'age':'18'}) 4 5 son=ET.SubElement(root,'root',{'age':'18'}) 6 ET.SubElement(son,'haha',{'bb':'fhfhf'}) 7 8 tree = ET.ElementTree(root) 9 tree.write('aha.xml')
结果