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

Example tutorial on building XML tree structure in Python

零下一度
Release: 2017-07-02 10:50:07
Original
1103 people have browsed it

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)   #输出在标准输出中,也可写在文件中
Copy after login

Output results:


<color>black</color>
Copy after login

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)  #打印树结构
Copy after login

Output result:


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

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 "<" in the element content, it cannot be input directly because "<"

##Character entity<>&'##"

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Symbol
<
>
&