How to Use python to generate xml
Recently, you have to use python to generate an xml file. Because some content is in Chinese, CDATA is used in the original xml file. The library used by the previous python program does not have a method to create this region. I had to study it for a long time. Finally, the method of from lxml import etree is used. Here we will share the available python programs. For your reference. After testing, this code can directly run and generate content in xml format. Online Reference is mainly http://lxml.de/api/index.html this web page. Copy code 1 #-*-coding: UTF-8-*-2 import sys 3 import time 4 import string 5 6 from lxml import etree 7 8 9 # Set the default character set to UTF8. Otherwise, transcoding may fail. 10 default_encoding = 'utf- 8'11 if sys. getdefaultencoding ()! = Default_encoding: 12 reload (sys) 13 sys. setdefaultencoding (default_encoding) 14 15 def create_xml (): 16 17 data = etree. element ("data") 18 #1 interface_version19 interface_version_txt = '5' 20 interface_version = etree. subElement (data, 'interface _ version') 21 interface_version.text = interface_version_txt22 #2 site23 site_txt = 'www .xxx.com '24 site = etree. subElement (data, 'SITE') 25 site. text = site_txt26 #3 lastmod27 lastmod_txt = time. strftime ('% Y-% m-% d', time. localtime () 28 lastmod = etree. subElement (data, 'lastmod') 29 lastmod. text = lastmod_txt30 #5 app31 app = etree. subElement (data, 'app') 32 #6 title 33 title_txt = u '% s' %' truth adventure '34 title_txt = etree. CDATA (title_txt) 35 title = etree. subElement (app, 'title') 36 title. text = title_txt37 #7 appid38 appid = etree. subElement (app, 'appid ') 39 appid. text = '% s' % '000000' 40 41 dataxml = etree. tostring (data, pretty_print = True, encoding = "UTF-8", method = "xml", xml_declaration = True, standalone = None) 42 print dataxml43 44 47 if _ name _ = '_ main _': 48 create_xml ()