1. 程式人生 > >Python中模塊之xml的講解

Python中模塊之xml的講解

color 二級 true ron eight ril tag mov width

xml模塊的功能介紹

這裏主要講解xml模塊下的etree.ElementTree類。

1. 創建

具體代碼如下

import xml.etree.ElementTree as XM
namelist1 = XM.Element("namelist1")#創建標簽
name1 = XM.SubElement(namelist1,"name",attrib={"enrolled":"yes"})#創建子標簽
age1 = XM.SubElement(name1,"age",attrib={"checked":"33"})#創建下一級子標簽
sex1 = XM.SubElement(name1,"sex",)#創建最後一級子標簽
sex1.text = ‘man‘#對最後一級子標簽添加text屬性
name2 = XM.SubElement(namelist1,"name",attrib={"enrolled":"no"})
age2 = XM.SubElement(name2,"age",attrib={‘actual‘:‘19‘})
sex2 = XM.SubElement(name2,‘sex‘)
sex2.text = ‘gril‘
et = XM.ElementTree(namelist1) #生成文檔對象
et.write("test.xml", encoding="utf-8",xml_declaration=True)
XM.dump(namelist1) #打印生成的格式

2. 修改

具體代碼如下

xm_data = XM.parse(‘test.xml‘)
data_root = xm_data.getroot()#獲取第一級標簽
for i in data_root.iter(‘sex‘):
    i.text = ‘Super‘ + i.text
# for j in data_root.iter(‘age‘):#遍歷出的屬性為字典類型,可參考字典修改方法進行修改。
#     print(j.attrib)
xm_data.write(‘test.xml‘)

3. 查詢

具體代碼如下

xm_data = XM.parse(‘test.xml‘)
data_root = xm_data.getroot()#獲取第一級標簽
print(data_root)
for name in data_root:#遍歷第一級標簽
    print(name.tag,name.attrib)
    for age in name:#遍歷第二級標簽
        print(age.tag,age.text)
for names in data_root.iter(‘name‘):#過濾性變遍歷
    print(names.tag,names.text)

4. 刪除

具體代碼如下 xmdata = XM.parse(‘test.xml‘) dataroot = xmdata.getroot()#獲取第一級標簽 for name in dataroot: for age in name.findall(‘age‘): if age.attrib.get(‘actual‘): name.remove(age) xm_data.write(‘test.xml‘)

Python中模塊之xml的講解