Andrius
Andrius

Reputation: 21128

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.

Upvotes: 19

Views: 11242

Answers (3)

Engensmax
Engensmax

Reputation: 129

For those also wanting to solve this in one line, there is the walrus operator since python 3.8

Therefore

from lxml import etree

root = etree.Element('root')
(a := etree.SubElement(root, 'a')).text = 'some text'

And for the daring ones

from lxml import etree
(a := etree.SubElement(root:= etree.Element('root'), 'a')).text = 'some text'

Upvotes: 0

Sharon Dwilif K
Sharon Dwilif K

Reputation: 1228

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.

Upvotes: 10

Vijay Kumar
Vijay Kumar

Reputation: 191

How about the following?

etree.SubElement(root, "a").text = "some text"

Works only if you do not need to assign the resultant element to a variable.

Upvotes: 17

Related Questions