19

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.

Andrius
  • 19,658
  • 37
  • 143
  • 243

2 Answers2

15

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.

Vijay Kumar
  • 161
  • 4
10

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.

Sharon Dwilif K
  • 1,218
  • 9
  • 17