lxml - create instances of custom classes manually

Viewed 246

I'm using lxml to create custom objects by parsing XML, I wonder if there's a direct way to do the inverse: Create instances of those classes, use the methods of the custom classes and then serialize them to XML

Normal use case, create objects by parsing 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()

gives:

True
sometext, someothertext

I would like to create an instance of TextElement in order to have access to its methods and then serialize it afterwards. I could do this:

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

This seems wrong (or let's say inefficient) to me

0 Answers
Related