Python XML generation

Source: Internet
Author: User

You are recently using Python to generate an XML-formatted file.  Because some of the content is in Chinese, the XML file uses a CDATA section.  Finally, I used the from lxml import etree this. 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.


#-*-Coding:utf-8-*-import sysimport timeimport string from lxml import etree# set the default character set to UTF8 or sometimes problems with transcoding default_encoding = ' Utf-8 ' if sys.getdefaultencoding ()! = default_encoding:reload (SYS) sys.setdefaultencoding (default_encoding) def c Reate_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 #2 Site Site_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 ') Lastmod.text = lastmod_txt #5 app = etree. subelement (data, ' app ') #6 title Title_txt = U '%s '% ' true words big adventure ' Title_txt = etree. CDATA (title_txt) title = Etree. subelement (app, ' title ') Title.text = title_txt #7 appid appid = etree.  subelement (app, ' AppID ') Appid.text = '%s '% ' 222 '  DataXML = etree.tostring (data, Pretty_print=true, encoding= "UTF-8", method= "xml", Xml_declaration=true, standalone= None) Print DataXML if __name__ = = ' __main__ ': Create_xml ()


Python XML generation

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.