How to generate XML using Python

Source: Internet
Author: User
Tags cdata

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

Related Article

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.