Python example tutorial for building an XML tree structure

Source: Internet
Author: User
This article mainly introduced the Python constructs the XML tree structure the method, unifies the example form to analyze the Python creation and the print XML number structure implementation step and the related operation skill, needs the friend can refer to the next

The example in this article describes how Python constructs the XML tree structure. Share to everyone for your reference, as follows:

1. Building XML Elements


#encoding =utf-8from xml.etree Import elementtree as Etimport Sysroot=et. Element (' color ')  #用Element类构建标签root. text= (' black ')     #设置元素内容tree =et. ElementTree (Root)  #创建数对象, the parameter is the root node object Tree.write (sys.stdout)   #输出在标准输出中, can also be written in the file

Output Result:


<color>black</color>

2. Building a complete XML tree structure


#encoding =utf-8from xml.etree Import elementtree as Etimport Sysroot=et. Element (' goods ') name_con=[' YHB ', ' Lwy ']size_con=[' 175 ', ' the ']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>

Predefined character entities in the 3.XML specification

The so-called character entity is a special character in an XML document, such as "<" in the content of an element that cannot be entered directly because "<"

character entity symbol
< <
; ;
& &
'
"
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.