Home > Article > Backend Development > Example tutorial on building XML tree structure in Python
This article mainly introduces the method of Python to build an XML tree structure. It analyzes the implementation steps and related operating techniques of creating and printing xml number structures in Python based on examples. Friends in need can refer to the following
The example in this article describes how Python builds an XML tree structure. Share it with everyone for your reference, the details are as follows:
1. Construct XML elements
#encoding=utf-8 from xml.etree import ElementTree as ET import sys root=ET.Element('color') #用Element类构建标签 root.text=('black') #设置元素内容 tree=ET.ElementTree(root) #创建数对象,参数为根节点对象 tree.write(sys.stdout) #输出在标准输出中,也可写在文件中
Output results:
<color>black</color>
2. Build a complete XML tree structure
##
#encoding=utf-8 from xml.etree import ElementTree as ET import sys root=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) #打印树结构Output result:
<goods><skirt index="0"><name>yhb</name><size>175</size></skirt><skirt index="1"><name>lwy</name><size>170</size></skirt></goods>
3. The predetermined character entities in the XML specification
The so-called character entities are the special characters in the XML document , if there is "71292663c174733570ddb44c7e71c621
&>
'&
##"
The above is the detailed content of Example tutorial on building XML tree structure in Python. For more information, please follow other related articles on the PHP Chinese website!