Python之xml模块


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"?>

    "Liechtenstein">
        "yes">2
        2008
        141100
        "Austria" direction="E"/>
        "Switzerland" direction="W"/>
    
    "Singapore">
        "yes">5
        2011
        59900
        "Malaysia" direction="N"/>
    
    "Panama">
        "yes">69
        2011
        13600
        "Costa Rica" direction="W"/>
        "Colombia" direction="E"/>
    


---

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)