import xml.etree.ElementTree as tree import io xml = '''<?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank updated="yes">69</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country> </data> ''' parse = tree.fromstring(xml) #type:tree.Element #根節點 for e in parse: #遍歷 print(e.tag) # 節點名稱 print(e.attrib.get('name'))#節點屬性 result = parse.findall('country') # 只能找到子節點 第一層 print(result) #[<Element 'country' at 0x0000000001DDE7C8>, <Element 'country' at 0x000000000291F908>, <Element 'country' at 0x000000000291FA98>] print([e for e in parse.iter('rank') if e.attrib.get('updated') == 'yes']) #遞歸遍歷所有 #父節點 parse 添加子節點 print(tree.SubElement(parse, 'test', attrib={'name': 'ceshi'})) #工廠方式添加子節點 print(tree.tostring(parse).decode('utf-8')) #輸出xml文檔
