You are recently using Python to generate an XML-formatted file. Because some of the content is in Chinese, the original XML file uses a CDATA section. There is no way to create this area in the library used by the previous Python program. Helpless study of the big half day. Finally, the method of the From lxml import etree This library is used. This is where you can share your running Python programs. For everyone's reference. After testing, this code can be run directly to generate XML format content. The main online reference is http://lxml.de/api/index.html this page.
1 #-*-coding:utf-8-*-2 ImportSYS3 Import Time4 Importstring5 6 fromlxmlImportetree7 8 9 #Set the default character set to UTF8 or there are times when transcoding can be problematic .TenDefault_encoding ='Utf-8' One ifSys.getdefaultencoding ()! =default_encoding: A Reload (SYS) - sys.setdefaultencoding (default_encoding) - the defcreate_xml (): - -data = etree. Element ("Data") - #1 interface_version +Interface_version_txt ='5' -Interface_version = etree. subelement (data,'interface_version') +Interface_version.text =Interface_version_txt A #2 Site atSite_txt ='www.xxx.com' -site = etree. subelement (data,'site') -Site.text =Site_txt - #3 Lastmod -Lastmod_txt = Time.strftime ('%y-%m-%d', Time.localtime ()) -Lastmod = etree. subelement (data,'Lastmod') inLastmod.text =Lastmod_txt - #5 Apps toApp = Etree. subelement (data,'app') + #6 Title -Title_txt = u'%s'%'The truth, the Big Adventure .' theTitle_txt =etree. CDATA (title_txt) *title = Etree. subelement (App,'title') $Title.text =Title_txtPanax Notoginseng #7 AppID -AppID = etree. subelement (App,'AppID') theAppid.text ='%s'%'222' + ADataXML = etree.tostring (data, Pretty_print=true, encoding="UTF-8", method="XML", Xml_declaration=true, standalone=None) the PrintDataXML + - - if __name__=='__main__': -Create_xml ()
How to generate XML using Python