''' xml 文件的讀取方法 ''' #!/usr/bin/env python # -*- coding: utf-8 -*- import xml.etree.ElementTree as ET from datetime import datetime tree = ET.parse("country.xml") root = tree.getroot() print "**************tag 根元素*********" print(root.tag, ":", root.attrib) # 打印根元素的tag和屬性 # find('nodeName'):表示在該節點下,查找其中第一個tag為nodeName的節點。 print "*#查找root節點下第一個tag為country的節點********" animNode = root.find('country') #查找root節點下第一個tag為country的節點 print(animNode.tag,animNode.attrib,animNode.text) print "**查找其中所有tag為nodeName的節點*****" # findall('nodeName'):表示在該節點下,查找其中所有tag為nodeName的節點 # animNode = root.findall('country') #查找root節點下所有 tag為country的節點 # print(animNode.tag,animNode.attrib,animNode.text) print "*刪除指定的節點的信息 保存文件*" animNode = root.find('country') if animNode.attrib['name'] == 'Liechtenstein': root.remove(animNode) tree.write('finish.xml') # 保存修改后的XML文件 cur_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') print "current time: ",cur_time # 遍歷xml文檔的第二層 for child in root: # 第二層節點的標簽名稱和屬性 print(child.tag,":", child.attrib) # 遍歷xml文檔的第三層 for children in child: # 第三層節點的標簽名稱和屬性 print(children.tag, ":", children.attrib)
