Python Method for converting objects to xml, pythonxml

Source: Internet
Author: User

Python Method for converting objects to xml, pythonxml

This example describes how to convert an object to xml in Python. We will share this with you for your reference. The details are as follows:

#-*-Coding: UTF-8-*-''' Created on 2010-4-20 @ author: worryss' ''' import xml. etree. elementTree as ETimport xml. dom. minidom as minidomfrom addrbook. domain import Personclass Converter (object): ''' implement mutual conversion between Python objects and xml ''' root = None # root node def _ init _ (self): pass @ staticmethod def createRoot (rootTag): ''' create the root node ''' root = ET. element (rootTag) return root @ staticmethod def getXmlString (element, defaul TEncoding = 'utf-8'): ''' the formatted xml string ''' try: rough_string = ET. tostring (element, defaultEncoding) reparsed = minidom. parseString (rough_string) return reparsed. toprettyxml (indent = "", encoding = defaultEncoding) handle T: print 'getxmlstring: the input node cannot be correctly converted to xml, check whether the input node is 'Return ''@ staticmethod def classToElements (classobj, rootTag = None): ''' Based on the instance of the input object, generate a node based on the property of the object and return the classobj list composed of nodes: The instance ro of the object. OtTag: root node name ''' attrs = None # Save the object's attribute set elelist = [] # node list try: attrs = classobj. _ dict __. keys () # Get all attributes of the object (that is, the member variable) except T: print 'classtoelements: the input object is invalid and the object attribute 'if attrs! = None and len (attrs)> 0: # for attr in attrs: attrvalue = getattr (classobj, attr) # Attribute Value # attribute node attrE = ET. element (attr) attrE. text = attrvalue # Add elelist to the node list. append (attrE) return elelist @ staticmethod def classToXML (classobj, rootTag = None): ''' the Python custom model class is converted to xml, and the xml root node is returned after successful conversion, otherwise, None classobj is returned: The instance rootTag of the object: root node name ''' try: classname = classobj. _ class __. _ name _ # class name if rootTag! = None: root = Converter. createRoot (rootTag) else: root = Converter. createRoot (classname) elelist = Converter. classToElements (classobj, rootTag) for ele in elelist: root. append (ele) return root failed T: print 'classtoxml: Conversion error. Please check whether the input object is correct 'Return None @ staticmethod def collectionToXML (listobj, rootTag = 'LIST '): ''''' set (list, tuples, and dictionaries) is converted to xml. If the conversion is successful, the xml root node is returned. Otherwise, None ''' try: classname = listobj is returned. _ class __. _ name _ # class name root = Converter. createRoot (rootTag) if isinstance (listobj, list) or isinstance (listobj, tuple): # list or tuples if len (listobj)> = 0: for obj in listobj: # itemE = Converter. classToXML (obj) root. append (itemE) elif isinstance (listobj, dict): # dictionary if len (listobj)> = 0: for key in listobj: # The object obj = listobj [key] itemE = Converter in the iteration dictionary. classToXML (obj) itemE. set ('key', key) root. append (itemE) else: print 'listtoxml: Conversion error. Input object: '+ classname +' is not set type. 'Return root failed T: print' collectionToXML: Conversion error, failed to convert the set to xml 'Return Noneif _ name _ = '_ main _': p1 = Person ('dredfsam ', 'mal', '123 ') p2 = Person ('dream', 'female ', 'R') p3 = Person ('score', 'male', 'sdf ') personList = {} personList ['p1'] = p1 personList ['p2'] = p2 personList ['p3'] = p3 # personList. append (p1) # personList. append (p2) # personList. append (p3) root = Converter. collectionToXML (personList) print Converter. getXmlString (root) # plist = (p1, p2, p3) # {'name': 'sdf '} # print type (plist ), isinstance (plist, list)

PS: Here are some online tools for xml operations for your reference:

Online XML/JSON conversion tools:
Http://tools.jb51.net/code/xmljson

Online formatting XML/online compression XML:
Http://tools.jb51.net/code/xmlformat

XMLOnline compression/formatting tools:
Http://tools.jb51.net/code/xml_format_compress

XMLCode Online formatting and beautification tools:
Http://tools.jb51.net/code/xmlcodeformat

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.