Python如何使用ElementTree解析xml
以country.xml為例,內(nèi)容如下:
<?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>
1.解析
1)調(diào)用parse()方法,返回解析樹(shù)
try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET tree = ET.parse("country.xml") # <class 'xml.etree.ElementTree.ElementTree'> root = tree.getroot() # 獲取根節(jié)點(diǎn) <Element 'data' at 0x02BF6A80>
2)調(diào)用from_string(),返回解析樹(shù)的根元素
import xml.etree.ElementTree as ET
data = open("country.xml").read()
root = ET.fromstring(data) # <Element 'data' at 0x036168A0>
3)調(diào)用ElementTree類(lèi)ElementTree(self, element=None, file=None) # 這里的element作為根節(jié)點(diǎn)
import xml.etree.ElementTree as ET
tree = ET.ElementTree(file="country.xml") # <xml.etree.ElementTree.ElementTree object at 0x03031390>
root = tree.getroot() # <Element 'data' at 0x030EA600>
1)簡(jiǎn)單遍歷
import xml.etree.ElementTree as ET tree = ET.parse("country.xml") root = tree.getroot() print(root.tag, ":", root.attrib) # 打印根元素的tag和屬性 # 遍歷xml文檔的第二層 for child in root: # 第二層節(jié)點(diǎn)的標(biāo)簽名稱(chēng)和屬性 print(child.tag,":", child.attrib) # 遍歷xml文檔的第三層 for children in child: # 第三層節(jié)點(diǎn)的標(biāo)簽名稱(chēng)和屬性 print(children.tag, ":", children.attrib)
可以通過(guò)下標(biāo)的方式直接訪問(wèn)節(jié)點(diǎn)
# 訪問(wèn)根節(jié)點(diǎn)下第一個(gè)country的第二個(gè)節(jié)點(diǎn)year,獲取對(duì)應(yīng)的文本
year = root[0][1].text # 2008
2)ElementTree提供的方法
find(match) # 查找第一個(gè)匹配的子元素, match可以時(shí)tag或是xpaht路徑
findall(match) # 返回所有匹配的子元素列表
findtext(match, default=None) #
iter(tag=None) # 以當(dāng)前元素為根節(jié)點(diǎn) 創(chuàng)建樹(shù)迭代器,如果tag不為None,則以tag進(jìn)行過(guò)濾
iterfind(match) #
例子:
# 過(guò)濾出所有neighbor標(biāo)簽
for neighbor in root.iter("neighbor"):
print(neighbor.tag, ":", neighbor.attrib)
# 遍歷所有的counry標(biāo)簽
for country in root.findall("country"):
# 查找country標(biāo)簽下的第一個(gè)rank標(biāo)簽
rank = country.find("rank").text
# 獲取country標(biāo)簽的name屬性
name = country.get("name")
print(name, rank)
1) 屬性相關(guān)
# 將所有的rank值加1,并添加屬性u(píng)pdated為yes for rank in root.iter("rank"): new_rank = int(rank.text) + 1 rank.text = str(new_rank) # 必須將int轉(zhuǎn)為str rank.set("updated", "yes") # 添加屬性 # 再終端顯示整個(gè)xml ET.dump(root) # 注意 修改的內(nèi)容存在內(nèi)存中 尚未保存到文件中 # 保存修改后的內(nèi)容 tree.write("output.xml")
import xml.etree.ElementTree as ET tree = ET.parse("output.xml") root = tree.getroot() for rank in root.iter("rank"): # attrib為屬性字典 # 刪除對(duì)應(yīng)的屬性u(píng)pdated del rank.attrib['updated'] ET.dump(root)
小結(jié): 關(guān)于classxml.etree.ElementTree.Element 屬性相關(guān)
- attrib 為包含元素屬性的字典
- keys() 返回元素屬性名稱(chēng)列表
- items() 返回(name,value)列表
- get(key, default=None) 獲取屬性
- set(key, value) # 跟新/添加 屬性
- del xxx.attrib[key] # 刪除對(duì)應(yīng)的屬性
2) 節(jié)點(diǎn)/元素 相關(guān)
刪除子元素remove()
import xml.etree.ElementTree as ET tree = ET.parse("country.xml") root = tree.getroot() # 刪除rank大于50的國(guó)家 for country in root.iter("country"): rank = int(country.find("rank").text) if rank > 50: # remove()方法 刪除子元素 root.remove(country) ET.dump(root)
添加子元素
代碼:
import xml.etree.ElementTree as ET tree = ET.parse("country.xml") root = tree.getroot() country = root[0] last_ele = country[len(list(country))-1] last_ele.tail = '\n\t\t' # 創(chuàng)建新的元素, tag為test_append elem1 = ET.Element("test_append") elem1.text = "elem 1" # elem.tail = '\n\t' country.append(elem1) # SubElement() 其實(shí)內(nèi)部調(diào)用的時(shí)append() elem2 = ET.SubElement(country, "test_subelement") elem2.text = "elem 2" # extend() elem3 = ET.Element("test_extend") elem3.text = "elem 3" elem4 = ET.Element("test_extend") elem4.text = "elem 4" country.extend([elem3, elem4]) # insert() elem5 = ET.Element("test_insert") elem5.text = "elem 5" country.insert(5, elem5) ET.dump(country)
效果:
添加子元素方法總結(jié):
- append(subelement)
- extend(subelements)
- insert(index, element)
4.創(chuàng)建xml文檔
想創(chuàng)建root Element,然后創(chuàng)建SubElement,最后將root element傳入ElementTree(element),創(chuàng)建tree,調(diào)用tree.write()方法寫(xiě)入文件
對(duì)于創(chuàng)建元素的3個(gè)方法: 使用ET.Element、Element對(duì)象的makeelement()方法以及ET.SubElement
import xml.etree.ElementTree as ET def subElement(root, tag, text): ele = ET.SubElement(root, tag) ele.text = text ele.tail = '\n' root = ET.Element("note") to = root.makeelement("to", {}) to.text = "peter" to.tail = '\n' root.append(to) subElement(root, "from", "marry") subElement(root, "heading", "Reminder") subElement(root, "body", "Don't forget the meeting!") tree = ET.ElementTree(root) tree.write("note.xml", encoding="utf-8", xml_declaration=True)
效果:
由于原生保存的XML時(shí)默認(rèn)無(wú)縮進(jìn),如果想要設(shè)置縮進(jìn)的話(huà), 需要修改保存方式
代碼:
import xml.etree.ElementTree as ET from xml.dom import minidom def subElement(root, tag, text): ele = ET.SubElement(root, tag) ele.text = text def saveXML(root, filename, indent="\t", newl="\n", encoding="utf-8"): rawText = ET.tostring(root) dom = minidom.parseString(rawText) with open(filename, 'w') as f: dom.writexml(f, "", indent, newl, encoding) root = ET.Element("note") to = root.makeelement("to", {}) to.text = "peter" root.append(to) subElement(root, "from", "marry") subElement(root, "heading", "Reminder") subElement(root, "body", "Don't forget the meeting!") # 保存xml文件 saveXML(root, "note.xml")
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- python標(biāo)準(zhǔn)庫(kù)ElementTree處理xml
- Python使用ElementTree美化XML格式的操作
- 利用 Python ElementTree 生成 xml的實(shí)例
- Python3 xml.etree.ElementTree支持的XPath語(yǔ)法詳解
- Python利用ElementTree模塊處理XML的方法詳解
- python xml.etree.ElementTree遍歷xml所有節(jié)點(diǎn)實(shí)例詳解
- Python中使用ElementTree解析XML示例
- python網(wǎng)絡(luò)編程學(xué)習(xí)筆記(八):XML生成與解析(DOM、ElementTree)
- python通過(guò)ElementTree操作XML獲取結(jié)點(diǎn)讀取屬性美化XML
- python通過(guò)ElementTree操作XML
相關(guān)文章
用Python實(shí)現(xiàn)二叉樹(shù)、二叉樹(shù)非遞歸遍歷及繪制的例子
今天小編就為大家分享一篇用Python實(shí)現(xiàn)二叉樹(shù)、二叉樹(shù)非遞歸遍歷及繪制的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-08-08pywinauto自動(dòng)化測(cè)試使用經(jīng)驗(yàn)
本文主要介紹了pywinauto自動(dòng)化測(cè)試使用經(jīng)驗(yàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03python自定義函數(shù)實(shí)現(xiàn)一個(gè)數(shù)的三次方計(jì)算方法
今天小編就為大家分享一篇python自定義函數(shù)實(shí)現(xiàn)一個(gè)數(shù)的三次方計(jì)算方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01jupyter-lab設(shè)置自啟動(dòng)及遠(yuǎn)程連接開(kāi)發(fā)環(huán)境
本文主要介紹了jupyter-lab設(shè)置自啟動(dòng)及遠(yuǎn)程連接開(kāi)發(fā)環(huán)境,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02Python的numpy庫(kù)下的幾個(gè)小函數(shù)的用法(小結(jié))
這篇文章主要介紹了Python的numpy庫(kù)下的幾個(gè)小函數(shù)的用法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07Python寫(xiě)的英文字符大小寫(xiě)轉(zhuǎn)換代碼示例
這篇文章主要介紹了Python寫(xiě)的英文字符大小寫(xiě)轉(zhuǎn)換代碼示例,本文例子相對(duì)簡(jiǎn)單,本文直接給出代碼實(shí)例,需要的朋友可以參考下2015-03-03Python 爬蟲(chóng)性能相關(guān)總結(jié)
這篇文章主要介紹了Python 爬蟲(chóng)性能的相關(guān)資料,文中講解非常詳細(xì),幫助大家更好的理解和學(xué)習(xí)爬蟲(chóng),感興趣的朋友可以了解下2020-08-08