Python之xml模块
xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但是使用起来更简单。在json还没诞生时,大家选择xml,现在很多传统公司的接口主要还是xml。
xml格式,就是通过<>节点来区别数据结构的。
xml协议在各个语言里都是支持的,在Python中可以用以下模块操作xml
print(root.iter('year')) #全文搜素
print(root.find('country')) #在root的子节点找,只找一个
print(root.findall('country')) #在root子节点找,找所有
#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>
---
import xml.etree.ElementTree as ET
tree = ET.parse("xmltest.xml")
root = tree.getroot()
print(root.tag)
#遍历xml文档
for child in root:
print('========>',child.tag,child.attrib,child.attrib['name'])
for i in child:
print(i.tag,i.attrib,i.text)
#只遍历year 节点
for node in root.iter('year'):
print(node.tag,node.text)