一、前言
解析xml文件,使用xml.etree.ElementTree模块实现了一个简单高效的API,用于解析和创建XML数据。
二、知识点
知识点1:解析 XML
#举例1:可以通过从文件中读取来导入此数据:
import lxml.etree as LET
tree = LET.parse('country_data.xml')
root = tree.getroot()
#举例2:可以迭代的子节点
""" for child in root:
print(child.tag, child.attrib) """
#举例3:子级是可以嵌套的,我们可以通过索引访问特定的子级节点
""" print(root[0][2].text) """
#举例4:递归遍历其下的所有子树(包括子级,子级的子级,等等)
#iter() 函数用来生成迭代器。iterator 迭代器,迭代程序
"""
for year in root.iter('year'):
print(year.tag)
"""
二、测试用xml--country_data.xml
<?xml version='1.0' encoding='UTF-8'?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>