python:Xml

 

<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>
testXML
import xml.etree.ElementTree as ET
tree = ET.parse("xml_test.xml")
root = tree.getroot()
print(root)
print(root.tag)
# 遍历xml文档
for child in root:
    print(child.tag, child.attrib)
    for i in child:
        print(i.tag, i.text,i.attrib)
遍历xml文档
import xml.etree.ElementTree as ET
tree = ET.parse("xml_test.xml")
root = tree.getroot()
for node in root.iter('year'):
    print(node.tag, node.text)
只遍历year 节点

 

posted @ 2016-10-04 17:30  梅子472  阅读(169)  评论(0编辑  收藏  举报