python基礎 xml解析

xml.etree.ElementTree的經常使用API

一、解析xmlspa

<?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的兩種方式:code

import xml.etree.ElementTree as ET
# 一、從文件讀取
tree = ET.parse('country_data.xml')
root = tree.getroot()
#二、 從字符串讀取
root = ET.fromstring(country_data)

element對象的經常使用屬性:xml

  1. tag:string對象,表示標籤內容。對象

  2. attrib:dictionary對象,表示標籤的屬性。blog

  3. text:string對象,表示element的內容。遞歸

  4. tail:string對象,表示element閉合以後的尾跡。索引

獲子節點的方式:element

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

 

查找節點的經常使用APIrem

  • 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>

 

二、新建一個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>
 
相關文章
相關標籤/搜索