好吧,您可以使用Etree、LXML Etree或美丽的汤之类的东西。这些可以做到这一点,甚至更多。但是,有时您可能想要添加一些对其中任何一个都不实用的实现细节,因此您可以自己实现 ETreeFactory 之类的东西,或者至少了解如何继续执行此操作。这个例子做得不是特别好,但应该给你一个提示。
class XmlMixin(list):
"""
simple class that provides rudimentary
xml serialisation capabiities. The class
class uses attribute child that is a list
for recursing the structure.
"""
def __init__(self, *children):
list.__init__(self, children)
def to_xml(self):
data = '<%(tag)s>%(internal)s</%(tag)s>'
tag = self.__class__.__name__.lower()
internal = ''
for child in self:
try:
internal += child.to_xml()
except:
internal += str(child)
return data % locals()
# some example classes these could have
# some implementation details
class Root(XmlMixin):
pass
class View(XmlMixin):
pass
class Config(XmlMixin):
pass
class A_Header(XmlMixin):
pass
root = Root(
View(
Config('my config'),
A_Header('cool stuff')
)
)
#add stuff to the hierarchy
root.append(
View(
Config('other config'),
A_Header('not so cool')
)
)
print root.to_xml()
但是就像我说的那样,使用一些库函数代替你不需要实现这么多,你也会得到一个读者。很难实现 from_xml 也不难。
更新:将类更改为从列表继承。这使它更好地添加/删除树中的元素形式。添加了显示如何在初始创建后扩展树的示例。