Python實現(xiàn)對象轉(zhuǎn)換為xml的方法示例
本文實例講述了Python實現(xiàn)對象轉(zhuǎn)換為xml的方法。分享給大家供大家參考,具體如下:
# -*- coding:UTF-8 -*-
'''''
Created on 2010-4-20
@author: 憂里修斯
'''
import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom
from addrbook.domain import Person
class Converter(object):
'''''
實現(xiàn)Python對象與xml之間的相互轉(zhuǎn)換
'''
root = None#根節(jié)點
def __init__(self):
pass
@staticmethod
def createRoot(rootTag):
'''''
創(chuàng)建根節(jié)點
'''
root = ET.Element(rootTag)
return root
@staticmethod
def getXmlString(element,defaultEncoding='utf-8'):
'''''
根據(jù)節(jié)點返回格式化的xml字符串
'''
try:
rough_string = ET.tostring(element, defaultEncoding)
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" " , encoding=defaultEncoding)
except:
print 'getXmlString:傳入的節(jié)點不能正確轉(zhuǎn)換為xml,請檢查傳入的節(jié)點是否正確'
return ''
@staticmethod
def classToElements(classobj,rootTag=None):
'''''
根據(jù)傳入的對象的實例,根據(jù)對象的屬性生成節(jié)點,返回由節(jié)點組成的列表
classobj:對象的實例
rootTag:根節(jié)點名稱
'''
attrs = None#保存對象的屬性集
elelist = []#節(jié)點列表
try:
attrs = classobj.__dict__.keys()#獲取該對象的所有屬性(即成員變量)
except:
print 'classToElements:傳入的對象非法,不能正確獲取對象的屬性'
if attrs != None and len(attrs) > 0:#屬性存在
for attr in attrs:
attrvalue = getattr(classobj, attr)#屬性值
#屬性節(jié)點
attrE = ET.Element(attr)
attrE.text = attrvalue
#加入節(jié)點列表
elelist.append(attrE)
return elelist
@staticmethod
def classToXML(classobj,rootTag=None):
'''''
Python自定義模型類轉(zhuǎn)換成xml,轉(zhuǎn)換成功返回的是xml根節(jié)點,否則返回None
classobj:對象的實例
rootTag:根節(jié)點名稱
'''
try:
classname = classobj.__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
except:
print 'classToXML:轉(zhuǎn)換出錯,請檢查的傳入的對象是否正確'
return None
@staticmethod
def collectionToXML(listobj,rootTag='list'):
'''''
集合(列表、元組、字典)轉(zhuǎn)換為xml,轉(zhuǎn)換成功返回的是xml根節(jié)點,否則返回None
'''
try:
classname = listobj.__class__.__name__ #類名
root = Converter.createRoot(rootTag)
if isinstance(listobj, list) or isinstance(listobj, tuple):#列表或元組
if len(listobj) >= 0:
for obj in listobj:#迭代列表中的對象
itemE = Converter.classToXML(obj)
root.append(itemE)
elif isinstance(listobj, dict):#字典
if len(listobj) >= 0:
for key in listobj:#迭代字典中的對象
obj = listobj[key]
itemE = Converter.classToXML(obj)
itemE.set('key', key)
root.append(itemE)
else:
print 'listToXML:轉(zhuǎn)換錯誤,傳入的對象:'+classname+'不是集合類型'
return root
except:
print 'collectionToXML:轉(zhuǎn)換錯誤,集合轉(zhuǎn)換成xml失敗'
return None
if __name__ == '__main__':
p1 = Person('dredfsam','男','133665')
p2 = Person('dream','女','r')
p3 = Person('得分','男','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:這里再為大家提供幾款關(guān)于xml操作的在線工具供大家參考使用:
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson
在線格式化XML/在線壓縮XML:
http://tools.jb51.net/code/xmlformat
XML在線壓縮/格式化工具:
http://tools.jb51.net/code/xml_format_compress
XML代碼在線格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python操作xml數(shù)據(jù)技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python中Turtle庫改變畫筆(海龜)方向的兩種方法總結(jié)
turtle庫是python標(biāo)準(zhǔn)庫之一,入門級繪圖庫,import turtle之后即可使用,下面這篇文章主要給大家介紹了關(guān)于Python中Turtle庫改變畫筆(海龜)方向的兩種方法,需要的朋友可以參考下2022-11-11
如何利用pyinstaller打包Python程序為exe可執(zhí)行文件
這篇文章主要給大家介紹了關(guān)于如何利用pyinstaller打包Python程序為exe可執(zhí)行文件的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
Python?hug庫構(gòu)建快速可擴(kuò)展的Web API框架使用詳解
這篇文章主要介紹了Python?hug庫構(gòu)建快速可擴(kuò)展的Web API框架使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-02-02
python list等分并從等分的子集中隨機(jī)選取一個數(shù)
這篇文章主要介紹了python list等分并從等分的子集中隨機(jī)選取一個數(shù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
anaconda?部署Jupyter?Notebook服務(wù)器過程詳解
這篇文章主要為大家介紹了anaconda?部署Jupyter?Notebook服務(wù)器過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
python之模擬鼠標(biāo)鍵盤動作具體實現(xiàn)
這篇文章主要介紹了python之模擬鼠標(biāo)鍵盤動作具體實現(xiàn),有需要的朋友可以參考一下2013-12-12
Pycharm激活方法及詳細(xì)教程(詳細(xì)且實用)
這篇文章主要介紹了Pycharm激活方法及詳細(xì)教程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2020-05-05

