python_xml处理(一)

来源:互联网 发布:三国志9 知乎 编辑:程序博客网 时间:2024/05/29 05:01
<data>    <country name="Liechtenstein">        <rank updated="yes">2</rank>        <year>2023</year>        <gdppc>141100</gdppc>        <neighbor direction="E" name="Austria" />        <neighbor direction="W" name="Switzerland" />    </country>    <country name="Singapore">        <rank updated="yes">5</rank>        <year>2026</year>        <gdppc>59900</gdppc>        <neighbor direction="N" name="Malaysia" />    </country>    <country name="Panama">        <rank updated="yes">69</rank>        <year>2026</year>        <gdppc>13600</gdppc>        <neighbor direction="W" name="Costa Rica" />        <neighbor direction="E" name="Colombia" />    </country></data>
调用:from xml.etree import ElementTree as ET
使用: ET.XML() 将str类型转换成<class 'xml.etree.ElementTree.Element'>类型
tag 当前标签节点
iter('这个名字'),所有(这个名字)标签节点
find ("名字")寻找节点中包含的节点,只能找一层节点
arrtrib()标签内的属性
from xml.etree import ElementTree as ETroot = ET.XML(open('fist.xml','r',encoding='utf-8').read())print(type(root))#tag 是打印最外层标签节点print(root.tag)#迭代对应节点iter('要迭代节点的名字')for node in root.iter('year'):    print(node)#迭代下层节点for node in root:    #find 寻找节点中包含的节点,只能找一层节点    #text打印节点中内容    print(node.find('rank').text)    #打印节点对应属性    print(node.find('neighbor').attrib)
>>>>
<class 'xml.etree.ElementTree.Element'>data<Element 'year' at 0x000000845B0752C8><Element 'year' at 0x000000845B0754A8><Element 'year' at 0x000000845B075638>2{'name': 'Austria', 'direction': 'E'}5{'name': 'Malaysia', 'direction': 'N'}69{'name': 'Costa Rica', 'direction': 'W'}



原创粉丝点击