python三十七:xml模块
生活随笔
收集整理的這篇文章主要介紹了
python三十七:xml模块
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
??
# xml文件 <data><people name="liubein"><age must="yes">22</age><sex>man</sex><job name="emperor"/></people><people name="guanyu"><age>21</age><sex>man</sex><job name="General1"/></people><people name="zhangfei"><age>20</age><sex>man</sex><job name="General2"/></people> </data> import xml.etree.ElementTree as ETtree = ET.parse("xmlTest.xml") root = tree.getroot() print(root.tag)# 遍歷xml文檔 for child in root:# tag標(biāo)簽名稱, 標(biāo)簽attrib 屬性, text標(biāo)簽包含文本內(nèi)容print(child.tag, child.attrib)for i in child:print(i.tag, i.text)# 只遍歷某個(gè)節(jié)點(diǎn) for node in root.iter("age"):print(node.tag, node.text, node.attrib)# 修改 for node in root.iter('age'):new_age = int(node.text)+1node.text = str(new_age)# <age>20</age> 變成 <age updated="yes">21</age># 會(huì)在<age>標(biāo)簽中加上 updated="yes"屬性node.set("updated","yes")# 將修改的內(nèi)容寫到文件中 tree.write("new.xml")# 刪除某個(gè)節(jié)點(diǎn) for node in root.findall("people"):temp = int(node.find("age").text)if temp<21:root.remove(node)# 將刪除后的內(nèi)容保存到文件中 tree.write("new.xml")?
?創(chuàng)建xml文件
import xml.etree.ElementTree as ETnew = ET.Element("Food") # 生成xml對(duì)象fruit = ET.SubElement(new, "Fruit", attrib={"name":"watermelon"}) w = ET.SubElement(fruit, "weight") w.text = "50" c = ET.SubElement(fruit,"color") c.text = "blue"fruit = ET.SubElement(new, "Fruit", attrib={"name":"apple"}) w = ET.SubElement(fruit, "weight") w.text = "20" c = ET.SubElement(fruit,"color") c.text = "red"et = ET.ElementTree(new) # 生成文檔對(duì)象 et.write("test.xml", encoding="utf-8", xml_declaration=True)生成的xml文件如下:?
<?xml version='1.0' encoding='utf-8'?> <Food><Fruit name="watermelon"><weight>50</weight><color>blue</color></Fruit><Fruit name="apple"><weight>20</weight><color>red</color></Fruit> </Food>?
總結(jié)
以上是生活随笔為你收集整理的python三十七:xml模块的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。