一种合理的方法是使用python 描述符在对象上创建属性,这些属性知道如何对其自身进行序列化和反序列化。描述符是 python 用来创建 @property 装饰器的机制:包含 getter 和 setter 方法,并且可以具有本地状态,因此它们在您的数据和 xml 之间提供了一个很好的暂存地。再加上一个自动批量序列化/反序列化附加到对象的描述符的过程的类或装饰器,您就拥有了 C# XML 序列化系统的胆量。
通常,您希望代码看起来像这样(使用臭名昭著的 XML ISBN 示例:
@xmlobject("Book")
class Book( object ):
author = XElement( 'AuthorsText' )
title = XElement( 'Title' )
bookId = XAttrib( 'book_id' )
isbn = IntAttrib( 'isbn' )
publisher = XInstance( 'PublisherText', Publisher )
这里的分配语法是为实例中的所有字段(作者、标题等)创建类级描述符。每个描述符在其他 python 代码中看起来像一个常规字段,因此您可以执行以下操作:
book.author = 'Joyce, James'
等等。每个描述符在内部存储和 xml 节点或属性,当被调用序列化时,它将返回适当的 XML:
from xml.etree.cElementTree import ElementTree, Element
class XElement( object ):
'''
Simple XML serializable field
'''
def __init__( self, path):
self.path = path
self._xml = Element(path) # using an ElementTree or lxml element as internal storage
def get_xml( self, inst ):
return inst._xml
def _get_element( self ):
return self.path
def _get_attribute( self ):
return None
# the getter and setter push values into the underlying xml and return them from there
def __get__( self, instance, owner=None ):
myxml = self.get_xml( instance )
underlying = myxml.find( self.path )
return underlying.text
def __set__( self, instance, value, owner=None ):
myxml= self._get_xml( instance )
underlying = myxml.find( self.path )
underlying.text = value
相应的 XAttrib 类做同样的事情,除了在属性而不是元素中。
class XAttrib( XElement):
'''
Wraps a property in an attribute on the containing xml tag specified by 'path'
'''
def __get__( self, instance, owner=None ):
return self._get_xml( instance ).attrib[self.path]
# again, using ElementTree under the hood
def __set__( self, instance, value, owner=None ):
myxml = self._get_xml( instance )
has_element = myxml.get( self.path, 'NOT_FOUND' )
if has_element == 'NOT_FOUND':
raise Exception, "instance has no element path"
myxml.set( self.path, value )
def _get_element( self ):
return None #so outside code knows we are an attrib
def _get_attribute( self ):
return self.path
为了将它们联系在一起,拥有类需要在初始化时设置描述符,以便每个实例级描述符都指向拥有实例自己的 XML 元素中的一个 XML 节点。这样,对实例道具的更改会自动反映在所有者的 XML 中。
def create_defaults( target_cls):
# where target class is the serializable class, eg 'Book'
# here _et_xml() would return the class level Element, just
# as in the XElement and XAttribute. Good use for a decorator!
myxml = target_cls.get_xml()
default_attribs = [item for item in target_cls.__class__.__dict__.values()
if issubclass( item.__class__, XElement) ]
#default attribs will be all the descriptors in the target class
for item in default_attribs:
element_name = item._get_element()
#update the xml for the owning class with
# all the XElements
if element_name:
new_element = Element( element_name )
new_element.text = str( item.DEFAULT_VAL )
myxml.append( new_element )
# then update the owning XML with the attributes
for item in default_attribs:
attribpath = item._get_attribute()
if attrib:
myxml.set( attribpath, str( item.DEFAULT_VAL ) )
抱歉,如果此代码没有立即运行 - 我从一个工作示例中删除了它,但我可能在尝试使其可读并删除特定于我的应用程序的细节时引入了错误。