Skip to content Skip to sidebar Skip to footer

Python Lxml: Insert Text At Given Position Relatively To Subelements

I'd like to build the following XML element (in order to customize figure number formatting):
Figura 1.2 - Description of

Solution 1:

You need to use the tail property of the span element:

from lxml import etree as et
fc = et.Element("figcaption")
fn = et.SubElement(fc, "span", {'class':'fignum'})
fn.text = "Figure 1.2"
fn.tail = " - Description of figure."print(et.tostring(fc))
b'<figcaption><spanclass="fignum">Figure 1.2</span> - Description of figure.</figcaption>'

with ElementTree, elements have a text inside the element, and a tail after and outside the element.

With multiple children, the text of the parent is the text before the first child, all the other text inside the element will be assigned to the childrens' tail.

Some examples from another answer to this question which has since been deleted:

<elem>.text of elem</elem>.tail of elem
<elem>.text of elem<child1/><child2/></elem>.tail of elem
<elem>.text of elem<child1/>.tail of child1<child2/>.tail of child2</elem>.tail of elem
<elem>.text of elem<child1>.text of child1</child1>.tail of child1<child2/>.tail of child2</elem>.tail of elem

Post a Comment for "Python Lxml: Insert Text At Given Position Relatively To Subelements"