Python lxml subitem with text value?

Is it possible to somehow create an element with a text value by default? So I didn’t have to do that?

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 see no way to specify text in it.

+6
source share
2 answers

I don’t think there is a built-in way to do this, but if you find yourself doing it many times, it might be better to write a function that encapsulates the creation of a subitem and the text setting. 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") 

Note that with this, you cannot create an attribute named _text using keyword arguments; you will need to use the attribute keyword argument.

+3
source

What about the next one?

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

It only works if you do not need to assign the resulting element to a variable.

+1
source

All Articles