1. 程式人生 > >[python 學習] 使用 xml.etree.ElementTree 模塊處理 XML

[python 學習] 使用 xml.etree.ElementTree 模塊處理 XML

get try country cost 元素 rar ges 導入 nbsp

---恢復內容開始---

導入數據(讀文件和讀字符串)

本地文件 country_data.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
tree 
= ET.parse(country_data.xml) root = tree.getroot()

從字符串中讀取 xml

root = ET.fromstring(country_data_as_string)

Element.tag 、Element.text 和 Element.attributes

# root.tag 讀取 tag 名
# root.attrib 讀取 attributes
# root[0][1].rank 讀取文本值
print root.tag         #輸出根節點元素<data>的tag名:data
print root.attrib      #輸出根節點元素<data>的attributes(空值):{}
print root[0][2].text  #輸出第一個<country>的子元素<gdppc>的文本值:141100

技術分享

Element.iter()

# root.iter(‘neighbor‘)查找所有子孫元素
for neighbor in root.iter(neighbor):
    print neighbor.attrib

技術分享

find() 和 findall()

# find()返回第一個子元素
print root.find(country)
# fund() 返回所有子元素
print root.findall(country)

技術分享

照搬手冊:

https://docs.python.org/2/library/xml.etree.elementtree.html

[python 學習] 使用 xml.etree.ElementTree 模塊處理 XML