Python3的xml模塊及其使用

import xml.etree.ElementTree as ET

tree = ET.parse('xml_test')
root = tree.getroot()  # 獲取 根節點
print(root.tag)

# 遍歷xml文檔
for child in root:
    print(child.tag, child.attrib)  # 獲取下一級的標籤和屬性
    for i in child:
        print('  ', i.tag, i.text)  # 獲取再下一級的標籤和文本

# 只遍歷year 節點
for node in root.iter('year'):  # 在 根節點的子節點中過濾出標籤‘year’
    print(node.tag, node.text)  # 打印節點標籤和文本

# 修改
for node in root.iter('year'):
    new_year = int(node.text) + 1  # 修改獲取到的文本 (先轉爲int 型)
    node.text = str(new_year)  # 再轉爲string 型
    node.set("updated", "yes")  # 給指定標籤 賦值

tree.write("update.xml")  # 持久化

# 刪除node
for country in root.findall('country'):
    rank = int(country.find('rank').text)
    if rank > 50:
        root.remove(country)  # remove() 方法

tree.write('delete.xml')

操作文件:xml_test.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>

<!--xml數據-->

 要點:

  • parse('file') 解析文件
  • getroot() 獲取根節點
  • 根節點可遍歷:for child in root: child.tag,child.attrib 其中child.tag 獲取子節點標籤,child.attrib 獲取子節點屬性值
  • 上面的child 也是可遍歷對象: for i in child: i.tag , i.text 其中i.tag 獲取標籤,i.text 獲取文本
  • iter() 過濾字段 
  • findall() 匹配字段

# 序列化:內存中變成可存儲,可傳輸的過程稱之爲序列化

# json 流行,更簡單
# xml 過時的機制 在java

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章