o1278
o1278

Reputation: 11

How to implement methods for custom subelement in lxml?

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?

Upvotes: 1

Views: 57

Answers (0)

Related Questions