pythonlxml

Python lxml Subelement with text value?


Is it possible to somehow create element with default text value? So I would not need to do it like this?

from lxml import etree

root = etree.Element('root')
a = etree.SubElement(root, 'a')
a.text = 'some text' # Avoid this extra step?

I mean you can specify attributes in SubElement, but I don't see a way to specify text in it.


Solution

  • I don't think there is a builtin way to do that, but if you find yourself doing that many times, it may be better to write a function that encapsulates creating the sub element and setting the text. Example -

    def create_SubElement(_parent,_tag,attrib={},_text=None,nsmap=None,**_extra):
        result = etree.SubElement(_parent,_tag,attrib,nsmap,**_extra)
        result.text = _text
        return result
    

    And then create your element as -

    a = create_SubElement(root,'a',_text="Some text")
    

    Please note, with this you would not be able to create attribute with name _text using keyword arguments, you would need to use attrib keyword argument for that.