Example of how Python builds an XML tree structure

  • 2020-06-07 04:43:21
  • OfStack

This article illustrates Python's method of constructing XML tree structure. To share for your reference, specific as follows:

1. Build XML elements


#encoding=utf-8
from xml.etree import ElementTree as ET
import sys
root=ET.Element('color')  # with Element Class build tag 
root.text=('black')     # Set element content 
tree=ET.ElementTree(root)  # Creates a number object with the root node object as the argument 
tree.write(sys.stdout)   # The output is in standard output and can be written to a file 

Output results:


<color>black</color>

2. Complete XML tree structure was constructed


#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)  # An element with attributes 
  skirt=ET.SubElement(root,'skirt',index=('%s' %i)) # Equivalent to the above two sentences 
  name=ET.SubElement(skirt,'name') # Child elements 
  name.text=name_con[i]       # Node content 
  size=ET.SubElement(skirt,'size')
  size.text=size_con[i]
  tree=ET.ElementTree(root)
ET.dump(tree)  # Print tree structure 

Output results:


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

3. Character entities predetermined in the XML specification

Character entities are special characters in XML documents, such as" < "Cannot be entered directly because" < "

字符实体 符号
< <
> >
& &
&apos;
"

About escape character may refer to this site HTML/XML escape character table: http: / / tools ofstack. com/table/html_escape

PS: Here are some more online tools for xml:

Online XML/JSON interconversion Tool:
http://tools.ofstack.com/code/xmljson

Online format XML/ Online compression XML:
http://tools.ofstack.com/code/xmlformat

XML online compression/formatting tool:
http://tools.ofstack.com/code/xml_format_compress

XML code online formatting tool:
http://tools.ofstack.com/code/xmlcodeformat

More about Python related topics: interested readers to view this site "Python xml data operation skill summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article is helpful for Python programming.


Related articles: