SoFunction
Updated on 2025-03-02

Example of method for building XML tree structure in Python

This article describes the method of building XML tree structure in Python. Share it for your reference, as follows:

1. Build XML elements

#encoding=utf-8
from  import ElementTree as ET
import sys
root=('color')  #Build tags with Element class=('black')     #Set element contenttree=(root)  #Create a number object, the parameters are root node object()   #Output is in standard output, or can be written in a file

Output result:

<color>black</color>

2. Build a complete XML tree structure

#encoding=utf-8
from  import ElementTree as ET
import sys
root=('goods')
name_con=['yhb','lwy']
size_con=['175','170']
for i in range(2):
#  skirt=(root,'skirt')
# ['index']=('%s' %i) #Element with attributes  skirt=(root,'skirt',index=('%s' %i)) #Equivalent to the above two sentences  name=(skirt,'name') #Sube Elements  =name_con[i]       #Node Content  size=(skirt,'size')
  =size_con[i]
  tree=(root)
(tree)  #Print tree structure

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 specification

The so-called character entity is a special character in an XML document. If there is "<" in the element content, you cannot enter it directly because "<"

Character entity symbol
< <
> >
& &
&apos;
"

For escape characters, please refer to this siteHTML/XML escape character comparison tablehttp://tools./table/html_escape

PS: Here are a few online tools for your reference:

OnlineXML/JSON mutual conversion tool:
http://tools./code/xmljson

Online formattingXML/Online compressionXML
http://tools./code/xmlformat

XMLOnline compression/formatting tools:
http://tools./code/xml_format_compress

XMLCode online formatting and beautification tool:
http://tools./code/xmlcodeformat

For more information about Python-related content, please check out the topic of this site:Summary of Python's xml data skills》、《Python data structure and algorithm tutorial》、《Summary of Python Socket Programming Tips》、《Summary of Python function usage tips》、《Summary of Python string operation skills》、《Python introduction and advanced classic tutorials"and"Summary of Python file and directory operation skills

I hope this article will be helpful to everyone's Python programming.