Python example of a method that implements an object conversion to xml
- 2020-06-03 07:08:34
- OfStack
This article gives an example of how Python implements an object conversion to xml. To share for your reference, specific as follows:
# -*- coding:UTF-8 -*-
'''''
Created on 2010-4-20
@author: Theseus in sorrow
'''
import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom
from addrbook.domain import Person
class Converter(object):
'''''
implementation Python Object and the xml The transformation between the two
'''
root = None# The root node
def __init__(self):
pass
@staticmethod
def createRoot(rootTag):
'''''
Create the root node
'''
root = ET.Element(rootTag)
return root
@staticmethod
def getXmlString(element,defaultEncoding='utf-8'):
'''''
Returns formatted based on the node xml string
'''
try:
rough_string = ET.tostring(element, defaultEncoding)
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" " , encoding=defaultEncoding)
except:
print 'getXmlString: The incoming node could not be correctly converted to xml , check that the incoming node is correct '
return ''
@staticmethod
def classToElements(classobj,rootTag=None):
'''''
Based on the instance of the object passed in, the nodes are generated based on the properties of the object, and a list of nodes is returned
classobj : An instance of an object
rootTag : Root node name
'''
attrs = None# Save the set of properties for the object
elelist = []# The node list
try:
attrs = classobj.__dict__.keys()# Gets all the properties of the object ( Member variables )
except:
print 'classToElements: An invalid object was passed in, and the properties of the object could not be obtained correctly '
if attrs != None and len(attrs) > 0:# Attribute exists
for attr in attrs:
attrvalue = getattr(classobj, attr)# Attribute values
# An attribute node
attrE = ET.Element(attr)
attrE.text = attrvalue
# Add to node list
elelist.append(attrE)
return elelist
@staticmethod
def classToXML(classobj,rootTag=None):
'''''
Python Custom model classes converted to xml , the successful conversion returns xml Root node, otherwise returned None
classobj : An instance of an object
rootTag : Root node name
'''
try:
classname = classobj.__class__.__name__ # The name of the class
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
except:
print 'classToXML: Conversion error, check that the incoming object is correct '
return None
@staticmethod
def collectionToXML(listobj,rootTag='list'):
'''''
Collection (list, tuple, dictionary) converted to xml , the successful conversion returns xml Root node, otherwise returned None
'''
try:
classname = listobj.__class__.__name__ # The name of the class
root = Converter.createRoot(rootTag)
if isinstance(listobj, list) or isinstance(listobj, tuple):# A list or tuple
if len(listobj) >= 0:
for obj in listobj:# Iterate over the objects in the list
itemE = Converter.classToXML(obj)
root.append(itemE)
elif isinstance(listobj, dict):# The dictionary
if len(listobj) >= 0:
for key in listobj:# Iterate over the objects in the dictionary
obj = listobj[key]
itemE = Converter.classToXML(obj)
itemE.set('key', key)
root.append(itemE)
else:
print 'listToXML : Conversion error, incoming object: '+classname+' Not a collection type '
return root
except:
print 'collectionToXML : Conversion error, collection converted to xml failure '
return None
if __name__ == '__main__':
p1 = Person('dredfsam',' male ','133665')
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)
# print type(plist),isinstance(plist, list)
PS: Here are some more online tools for xml:
Online XML/JSON interconversion tool:
http://tools.ofstack.com/code/xmljson
XML online format/XML online compression:
http://tools.ofstack.com/code/xmlformat
XML online compression/formatting tool:
http://tools.ofstack.com/code/xml_format_compress
XML code online formatting tool:
http://tools.ofstack.com/code/xmlcodeformat
More about Python related topics: interested readers to view this site "Python xml data operation skill summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"
I hope this article has been helpful in Python programming.