利用python读写xml配置文件
程序员文章站
2022-12-20 22:51:20
大家好,今天来学习一下如何对xml配置文件进行读写。本人也是python小白,有不合适的地方大家多交流,谢谢大家。xml配置文件内容如下所示:1.写xml文件python代码如下import xml.etree.ElementTree as ETread_save = ET.Element("希望高中")li_ke = ET.SubElement(read_save,"理科",attrib = {"id":"001"}) wu_li = ET.SubElement(li_ke,"wu_...
大家好,今天来学习一下如何对xml配置文件进行读写。本人也是python小白,有不合适的地方大家多交流,谢谢大家。
xml配置文件内容如下所示:
1.写xml文件
python代码如下
import xml.etree.ElementTree as ET
read_save = ET.Element("希望高中")
li_ke = ET.SubElement(read_save,"理科",attrib = {"id":"001"})
wu_li = ET.SubElement(li_ke,"wu_li")
wu_li.text = "physical"
hua_xue = ET.SubElement(li_ke,"hua_xue")
hua_xue.text = "chemistry"
sheng_wu = ET.SubElement(li_ke,"sheng_wu")
sheng_wu.text = "biological"
wen_ke = ET.Element("文科",id = "002")
zheng_zhi = ET.SubElement(wen_ke,"zheng_zhi")
zheng_zhi.text = "political"
li_shi = ET.SubElement(wen_ke,"li_shi")
li_shi.text = "history"
di_li = ET.SubElement(wen_ke,"di_li")
di_li.text = "geography"
read_save.append(wen_ke)
et = ET.ElementTree(element = read_save)
et.write("read_save.xml",encoding = "utf-8",xml_declaration = True)
2.读xml配置文件
```python
class XML():
def __init__(self,path):
self.path = path
def read_xml(self):
tree = ET.parse(self.path)
root = tree.getroot()
tag0 = []
for i in range(len(root[0])):
tag0.append(root[0][i].tag)
text0 = []
for i in range(len(root[0])):
text0.append(root[0][i].text)
root0 = dict(zip(tag0,text0))
tag1 = []
for i in range(len(root[1])):
tag1.append(root[1][i].tag)
text1 = []
for i in range(len(root[1])):
text1.append(root[1][i].text)
root1 = dict(zip(tag1,text1))
info = {**root0,**root1}
return info
a = XML(path = "read_radical_save_server.xml")
b = a.read_xml()
再次谢谢大家的阅读。
本文地址:https://blog.csdn.net/m0_48432748/article/details/107450547