本文實(shí)例講述了Python構(gòu)建XML樹結(jié)構(gòu)的方法。分享給大家供大家參考,具體如下:
1.構(gòu)建XML元素
#encoding=utf-8from xml.etree import ElementTree as ETimport sysroot=ET.Element('color') #用Element類構(gòu)建標(biāo)簽root.text=('black') #設(shè)置元素內(nèi)容tree=ET.ElementTree(root) #創(chuàng)建數(shù)對(duì)象,參數(shù)為根節(jié)點(diǎn)對(duì)象tree.write(sys.stdout) #輸出在標(biāo)準(zhǔn)輸出中,也可寫在文件中輸出結(jié)果:
<color>black</color>
2.構(gòu)建完整XML樹結(jié)構(gòu)
#encoding=utf-8from xml.etree import ElementTree as ETimport sysroot=ET.Element('goods')name_con=['yhb','lwy']size_con=['175','170']for i in range(2):# skirt=ET.SubElement(root,'skirt')# skirt.attrib['index']=('%s' %i) #具有屬性的元素 skirt=ET.SubElement(root,'skirt',index=('%s' %i)) #相當(dāng)于上面兩句 name=ET.SubElement(skirt,'name') #子元素 name.text=name_con[i] #節(jié)點(diǎn)內(nèi)容 size=ET.SubElement(skirt,'size') size.text=size_con[i] tree=ET.ElementTree(root)ET.dump(tree) #打印樹結(jié)構(gòu)輸出結(jié)果:
<goods><skirt index="0"><name>yhb</name><size>175</size></skirt><skirt index="1"><name>lwy</name><size>170</size></skirt></goods>
3.XML規(guī)范中預(yù)定的字符實(shí)體
所謂字符實(shí)體就是XML文檔中的特殊字符,如元素內(nèi)容中有“<”時(shí)不能直接輸入,因?yàn)?ldquo;<”
| 字符實(shí)體 | 符號(hào) |
|---|---|
| < | < |
| > | > |
| & | & |
| ' | |
| " |
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選