Python構建XML樹結構的執行個體教程

來源:互聯網
上載者:User
這篇文章主要介紹了Python構建XML樹結構的方法,結合執行個體形式分析了Python建立與列印xml數結構的實現步驟與相關操作技巧,需要的朋友可以參考下

本文執行個體講述了Python構建XML樹結構的方法。分享給大家供大家參考,具體如下:

1.構建XML元素


#encoding=utf-8from xml.etree import ElementTree as ETimport sysroot=ET.Element('color')  #用Element類構建標籤root.text=('black')     #設定元素內容tree=ET.ElementTree(root)  #建立數對象,參數為根節點對象tree.write(sys.stdout)   #輸出在標準輸出中,也可寫在檔案中

輸出結果:


<color>black</color>

2.構建完整XML樹結構


#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)) #相當於上面兩句  name=ET.SubElement(skirt,'name') #子項目  name.text=name_con[i]       #節點內容  size=ET.SubElement(skirt,'size')  size.text=size_con[i]  tree=ET.ElementTree(root)ET.dump(tree)  #列印樹結構

輸出結果:


<goods><skirt index="0"><name>yhb</name><size>175</size></skirt><skirt index="1"><name>lwy</name><size>170</size></skirt></goods>

3.XML規範中預定的字元實體

所謂字元實體就是XML文檔中的特殊字元,如元素內容中有“<”時不能直接輸入,因為“<”

字元實體 符號
< <
> >
& &
'
"

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.