python操作XML格式文件的一些常見方法
前言
可擴(kuò)展標(biāo)記語言,是一種簡單的數(shù)據(jù)存儲語言,XML被設(shè)計用來傳輸和存儲數(shù)據(jù)
- 存儲,可用來存放配置文件,例: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)找第一個】 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)簽,找第一個 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個孫子 grandson1=ET.Element('grandson',{'name':'兒11'}) grandson2=ET.Element('grandson',{'name':'兒12'}) # 創(chuàng)建兩個孫子,與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)中沒有元素,用簡寫方式顯示例:<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)建兩個孫子,與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)建一個孫子 grandson1 = ET.SubElement(son1, "age", attrib={'name': '兒11'}) grandson1.text = '孫子' et = ET.ElementTree(root) #生成文檔對象 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) # 生成文檔對象 et.write("test.xml", encoding="utf-8")
補(bǔ)充:XML文件和JSON文件互轉(zhuǎn)
記錄工作中常用的一個小技巧
cmd控制臺安裝第三方模塊:
pip install xmltodict
1、XML文件轉(zhuǎn)為JSON文件
新建一個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庫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庫的unparse()json轉(zhuǎn)xml :param python_dict: python的字典對象 :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字典對象 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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python+ChatGPT制作一個AI實(shí)用百寶箱
ChatGPT最近在互聯(lián)網(wǎng)掀起了一陣熱潮,其高度智能化的功能能夠給我們現(xiàn)實(shí)生活帶來諸多的便利。本文就來用Python和ChatGPT制作一個AI實(shí)用百寶箱吧2023-02-02Python使用colorlog實(shí)現(xiàn)控制臺管理日志多種顏色顯示
colorlog 是一個 Python 日志庫,它可以讓你在控制臺中以彩色的方式顯示日志消息,使得日志更易于閱讀和理解,下面就跟隨小編一起來看看它的具體應(yīng)用吧2024-03-03Python容器類型轉(zhuǎn)換的3種方法實(shí)例
使用Python我們可以輕松地將數(shù)據(jù)轉(zhuǎn)換成不同的類型,下面這篇文章主要給大家介紹了關(guān)于Python容器類型轉(zhuǎn)換的3種方法,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05python爬蟲lxml庫解析xpath網(wǎng)頁過程示例
這篇文章主要為大家介紹了python爬蟲lxml庫解析xpath網(wǎng)頁的過程示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05