我通过解析XML使用lxml到create custom objects,我想知道是否有直接的方法来执行逆操作:创建这些类的实例,使用自定义类的方法然后将它们序列化为XML < / p>
正常用例,通过解析XML来创建对象:
from lxml import etree
class TextElement(etree.ElementBase):
def get_text(self):
return ', '.join([line.text for line in self.iter('line')])
# all parsed 'text' elements will be TextElement instances
parser = etree.XMLParser()
lookup = etree.ElementNamespaceClassLookup()
parser.set_element_class_lookup(lookup)
server_ns_lookup = lookup.get_namespace(None)
server_ns_lookup['text'] = TextElement
xml = """
<text>
<line>sometext</line>
<line>someothertext</line>
</text>
"""
res = etree.fromstring(xml, parser)
print isinstance(res, TextElement)
# take advantage of the TextElement methods...
print res.get_text()
给出:
True
sometext, someothertext
我想创建一个TextElement实例,以便访问其方法,然后将其序列化。 我能做到这一点:
E = objectify.ElementMaker(annotate=False)
text_element = E.text(
E.line('sometext'),
E.line('someothertext')
)
text_el = etree.fromstring(etree.tostring(text_element, pretty_print=True), parser)
# do some fancy stuff with the TextElement object
print text_el.get_text()
# and then serialize it for output
这对我来说似乎是错误的(或者说效率低下)