Home  >  Article  >  Backend Development  >  Example tutorial on building XML tree structure in Python

Example tutorial on building XML tree structure in Python

零下一度
零下一度Original
2017-07-02 10:50:071066browse

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(&#39;goods&#39;)
name_con=[&#39;yhb&#39;,&#39;lwy&#39;]
size_con=[&#39;175&#39;,&#39;170&#39;]
for i in range(2):
#  skirt=ET.SubElement(root,&#39;skirt&#39;)
#  skirt.attrib[&#39;index&#39;]=(&#39;%s&#39; %i)  #具有属性的元素
  skirt=ET.SubElement(root,&#39;skirt&#39;,index=(&#39;%s&#39; %i)) #相当于上面两句
  name=ET.SubElement(skirt,&#39;name&#39;) #子元素
  name.text=name_con[i]       #节点内容
  size=ET.SubElement(skirt,&#39;size&#39;)
  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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn