Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python lxml Subelement with text value?

Tags:

python

lxml

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.

like image 922
Andrius Avatar asked Oct 28 '15 09:10

Andrius


People also ask

Is XML and lxml are same?

lxml is a reference to the XML toolkit in a pythonic way which is internally being bound with two specific libraries of C language, libxml2, and libxslt. lxml is unique in a way that it combines the speed and XML feature completeness of these libraries with the simplicity of a native Python API.

Is lxml included in Python?

lxml has been downloaded from the Python Package Index millions of times and is also available directly in many package distributions, e.g. for Linux or macOS.


1 Answers

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.

like image 153
Vijay Kumar Avatar answered Sep 22 '22 01:09

Vijay Kumar