python操作XML格式文件的一些常見方法
前言
可擴(kuò)展標(biāo)記語言,是一種簡(jiǎn)單的數(shù)據(jù)存儲(chǔ)語言,XML被設(shè)計(jì)用來傳輸和存儲(chǔ)數(shù)據(jù)
- 存儲(chǔ),可用來存放配置文件,例:java配置文件
- 傳輸,網(wǎng)絡(luò)傳輸以這種格式存在,例:早期ajax傳輸數(shù)據(jù)等
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2023</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2026</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia" />
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2026</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica" />
<neighbor direction="E" name="Colombia" />
</country>
</data>
1. 讀取文件和內(nèi)容
#導(dǎo)包
from xml.etree import ElementTree as ET
# ET去打開xml文件
tree = ET.parse("files/xo.xml")
# 獲取根標(biāo)簽
root = tree.getroot()
print(root) # <Element 'data' at 0x7f94e02763b0>
2.讀取節(jié)點(diǎn)數(shù)據(jù)
獲取根標(biāo)簽
root = ET.XML(content)
查找節(jié)點(diǎn)【默認(rèn)找第一個(gè)】 find()
country_object = root.find("country")
print(country_object) #<Element 'country' at 0x0000020D57DFB220>
獲取節(jié)點(diǎn)標(biāo)簽 tag
country_object.tag #country
獲取節(jié)點(diǎn)屬性 attrib
country_object.attrib #{'name': 'Liechtenstein'}
獲取節(jié)點(diǎn)文本 text
gdppc_object.text #141100
循環(huán)節(jié)點(diǎn)
# 獲取data標(biāo)簽的孩子標(biāo)簽
for child in root:
print(child.tag, child.attrib)
#獲取child標(biāo)簽的孩子標(biāo)簽
for node in child:
print(node.tag, node.attrib, node.text)
查找所有標(biāo)簽 iter()
# 獲取data里面所有year標(biāo)簽
for child in root.iter('year'):
print(child.tag, child.text)
查找所有標(biāo)簽 findall()
# 查找所有的country標(biāo)簽
v1 = root.findall('country')
查找標(biāo)簽
# 查找country里面的rank標(biāo)簽,找第一個(gè)
v2 = root.find('country').find('rank')
3.修改和刪除節(jié)點(diǎn)
【修改和刪除內(nèi)容只在內(nèi)存中修改,沒有存到文件中,都要重新保存文件】
修改節(jié)點(diǎn)內(nèi)容
#修改rank文本
rank.text = "999"
tree = ET.ElementTree(root)
tree.write("new.xml", encoding='utf-8')
修改節(jié)點(diǎn)屬性
#修改rank屬性
rank.set('update', '2020-11-11')
tree = ET.ElementTree(root)
tree.write("new.xml", encoding='utf-8')
保存文件
tree = ET.ElementTree(root)
tree.write("new.xml", encoding='utf-8')
刪除節(jié)點(diǎn)
root.remove( root.find('country') )
tree = ET.ElementTree(root)
tree.write("new.xml", encoding='utf-8')
4.構(gòu)建文檔 方式一ET.Element()
<home>
<son name="兒1">
<grandson name="兒11"></grandson>
<grandson name="兒12"></grandson>
</son>
<son name="兒2"></son>
</home>
from xml.etree import ElementTree as ET
#創(chuàng)建根標(biāo)簽
root=ET.Element('home')
# 創(chuàng)建大兒子,與root還沒有關(guān)系
son1=ET.Element('son',{'name':'兒1'})
#創(chuàng)建小兒子,與root還沒有關(guān)系
son2=ET.Element('son',{'name':'兒2'})
#創(chuàng)建2個(gè)孫子
grandson1=ET.Element('grandson',{'name':'兒11'})
grandson2=ET.Element('grandson',{'name':'兒12'})
# 創(chuàng)建兩個(gè)孫子,與son1還沒有關(guān)系
son1.append(grandson1)
son1.append(grandson2)
# 把兒子添加到根節(jié)點(diǎn)
root.append(son1)
root.append(son2)
#root節(jié)點(diǎn)放到根節(jié)點(diǎn)中
tree=ET.ElementTree(root)
#保存xml文件
# short_empty_elements=True,節(jié)點(diǎn)中沒有元素,用簡(jiǎn)寫方式顯示例:<grandson name="兒11" />
tree.write('file/root.xml',encoding='utf-8',short_empty_elements=True)
方式二 標(biāo)簽.makeelement()
<famliy>
<son name="兒1">
<grandson name="兒11"></grandson>
<grandson name="兒12"></grandson>
</son>
<son name="兒2"></son>
</famliy>
from xml.etree import ElementTree as ET
# 創(chuàng)建根節(jié)點(diǎn)
root = ET.Element("famliy")
# 創(chuàng)建大兒子,與root還沒有關(guān)系
son1 = root.makeelement('son', {'name': '兒1'})
#創(chuàng)建小兒子,與root還沒有關(guān)系
son2 = root.makeelement('son', {"name": '兒2'})
# 創(chuàng)建兩個(gè)孫子,與son1還沒有關(guān)系
grandson1 = son1.makeelement('grandson', {'name': '兒11'})
grandson2 = son1.makeelement('grandson', {'name': '兒12'})
son1.append(grandson1)
son1.append(grandson2)
# 把兒子添加到根節(jié)點(diǎn)中
root.append(son1)
root.append(son2)
tree = ET.ElementTree(root)
tree.write('oooo.xml',encoding='utf-8')
方式三 標(biāo)簽.SubElement(),創(chuàng)建標(biāo)簽的子標(biāo)簽
<famliy>
<son name="兒1">
<age name="兒11">孫子</age>
</son>
<son name="兒2"></son>
</famliy>
from xml.etree import ElementTree as ET
# 創(chuàng)建根節(jié)點(diǎn)
root = ET.Element("famliy")
# 創(chuàng)建root節(jié)點(diǎn)的子標(biāo)簽大兒子
son1 = ET.SubElement(root, "son", attrib={'name': '兒1'})
# 創(chuàng)建root節(jié)點(diǎn)的子標(biāo)簽小兒子
son2 = ET.SubElement(root, "son", attrib={"name": "兒2"})
# 在大兒子中創(chuàng)建一個(gè)孫子
grandson1 = ET.SubElement(son1, "age", attrib={'name': '兒11'})
grandson1.text = '孫子'
et = ET.ElementTree(root) #生成文檔對(duì)象
et.write("test.xml", encoding="utf-8")
方式四
<user><![CDATA[你好呀]]</user>
from xml.etree import ElementTree as ET
# 創(chuàng)建根節(jié)點(diǎn)
root = ET.Element("user")
#<![CDATA[你好呀]]直接添加到文本里
root.text = "<![CDATA[你好呀]]"
et = ET.ElementTree(root) # 生成文檔對(duì)象
et.write("test.xml", encoding="utf-8")
補(bǔ)充:XML文件和JSON文件互轉(zhuǎn)
記錄工作中常用的一個(gè)小技巧
cmd控制臺(tái)安裝第三方模塊:
pip install xmltodict
1、XML文件轉(zhuǎn)為JSON文件
新建一個(gè)1.xml文件:
<note date="23/04/2022">
<to>tom</to>
<from>mary</from>
<msg>love</msg></note>
轉(zhuǎn)換代碼實(shí)現(xiàn):
import jsonimport xmltodictdef xml_to_json(xml_str):
"""parse是的xml解析器,參數(shù)需要
:param xml_str: xml字符串
:return: json字符串
"""
xml_parse = xmltodict.parse(xml_str)
# json庫(kù)dumps()是將dict轉(zhuǎn)化成json格式,loads()是將json轉(zhuǎn)化成dict格式。
# dumps()方法的ident=1,格式化json
json_str = json.dumps(xml_parse, indent=1)
return json_str
XML_PATH = './1.xml' # xml文件的路徑with open(XML_PATH, 'r') as f:
xmlfile = f.read()
with open(XML_PATH[:-3] + 'json', 'w') as newfile:
newfile.write(xml_to_json(xmlfile))
輸出結(jié)果(生成json文件):

2、JSON文件轉(zhuǎn)換為XML文件
新建test.json文件:
{
"student": {
"course": {
"name": "math",
"score": "90"
},
"info": {
"sex": "male",
"name": "name"
},
"stid": "10213"
}}
轉(zhuǎn)換代碼實(shí)現(xiàn):
import xmltodictimport jsondef json_to_xml(python_dict):
"""xmltodict庫(kù)的unparse()json轉(zhuǎn)xml
:param python_dict: python的字典對(duì)象
:return: xml字符串
"""
xml_str = xmltodict.unparse(python_dict)
return xml_str
JSON_PATH = './test.json' # json文件的路徑with open(JSON_PATH, 'r') as f:
jsonfile = f.read()
python_dict = json.loads(jsonfile) # 將json字符串轉(zhuǎn)換為python字典對(duì)象
with open(JSON_PATH[:-4] + 'xml', 'w') as newfile:
newfile.write(json_to_xml(python_dict))
輸出結(jié)果(生成xml文件):

總結(jié)
到此這篇關(guān)于python操作XML格式文件的文章就介紹到這了,更多相關(guān)python操作XML文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Pycharm中運(yùn)行程序在Python?console中執(zhí)行,不是直接Run問題
這篇文章主要介紹了Pycharm中運(yùn)行程序在Python?console中執(zhí)行,不是直接Run問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07
Python中的Descriptor描述符學(xué)習(xí)教程
簡(jiǎn)單來說,數(shù)據(jù)描述符是指實(shí)現(xiàn)了__get__、__set__、__del__方法的類屬性,等效于定義了三個(gè)方法的接口,下面就來詳細(xì)看一下Python中的Descriptor修飾符學(xué)習(xí)教程2016-06-06
python操作MySQL數(shù)據(jù)庫(kù)的方法分享
堅(jiān)持每天學(xué)一點(diǎn),每天積累一點(diǎn)點(diǎn),作為自己每天的業(yè)余收獲,這個(gè)文章是我在吃飯的期間寫的,利用自己零散的時(shí)間學(xué)了一下python操作MYSQL,所以整理一下2012-05-05
python多線程多并發(fā)啟動(dòng)appium服務(wù)的實(shí)現(xiàn)
使用Dos命令或者bat批處理來手動(dòng)啟動(dòng)appium服務(wù),啟動(dòng)效率低下,本文主要介紹了python多線程多并發(fā)啟動(dòng)appium服務(wù)的實(shí)現(xiàn),具有一定的 參考價(jià)值,感興趣的可以了解一下2024-02-02
python神經(jīng)網(wǎng)絡(luò)AlexNet分類模型訓(xùn)練貓狗數(shù)據(jù)集
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡(luò)AlexNet分類模型訓(xùn)練貓狗數(shù)據(jù)集,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05

