python基础 xml解析

xml.etree.ElementTree的常用API

1、解析xml

<?xml version="1.0"?>
<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>

读取xml的两种方式:

import xml.etree.ElementTree as ET
# 1、从文件读取
tree = ET.parse('country_data.xml')
root = tree.getroot()
#2、 从字符串读取
root = ET.fromstring(country_data)

element对象的常用属性:

  1. tag:string对象,表示标签内容。

  2. attrib:dictionary对象,表示标签的属性。

  3. text:string对象,表示element的内容。

  4. tail:string对象,表示element闭合之后的尾迹。

获子节点的方式:

# 1、使用循环
for child in root:
    print(child.tag, child.attrib)
# 2、使用索引
root[0][1]

 

查找节点的常用API

  • Element.iter():该方法会递归查找当前节点下的所有的子树
for neighbor in root.iter('neighbor'):
    print(neighbor.attrib)
'''
输出
{'name': 'Austria', 'direction': 'E'}
{'name': 'Switzerland', 'direction': 'W'}
{'name': 'Malaysia', 'direction': 'N'}
{'name': 'Costa Rica', 'direction': 'W'}
{'name': 'Colombia', 'direction': 'E'}
'''
  • Element.find():只查找当前节点的直接子节点。
  • Element.findall():只查找当前节点的直接子节点,返回所有元素列表

节点的删除和修改

  • Element.remove() : 删除节点
for country in root.findall('country'):
    rank = int(country.find('rank').text)
    if rank > 50:
        root.remove(country)
tree.write('output.xml')
<!--output.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> </data>

 

2、新建一个xml文档

  • SubElement(parent, tag, attrib={}, **extra) : 为指定元素创建一个字节点
a = ET.Element('a')
b = ET.SubElement(a,'b')
c = ET.SubElement(a, 'c')
d = ET.SubElement(c, 'd')
ET.dump(a)
# 输出:<a><b /><c><d /></c></a>
 

 

posted @ 2018-08-16 16:32  blackx  阅读(191)  评论(0编辑  收藏  举报