How to implement methods for custom subelement in lxml?

60 Views Asked by At

I'm trying to implement xml composed of custom objectified elements with methods. But subelements seem to lose methods associated with them.

In particular, this works:

from lxml import etree, objectify
M = objectify.ElementMaker(annotate=False)

class A(objectify.ObjectifiedElement):
    def insert_b(self, text):
        self.B = M.Whatever(text)

some_xml = A(A())
some_xml.insert_b("Text")
etree.tostring(some_xml)

Output:

b'<A><A/><B>Text</B></A>'

But this doesn't:

>>> some_xml.A.insert_b("Text")
Traceback (most recent call last)
    ...
AttributeError: 'lxml.etree._Element' object has no attribute 'insert_b'

The result I expected was b'<A><A><B>Text</B></A><B>Text</B></A>'.

Is there a way I can implement that?

0

There are 0 best solutions below