Python lxml:在相对于子元素的给定位置插入文本 [英] Python lxml: insert text at given position relatively to subelements

查看:64
本文介绍了Python lxml:在相对于子元素的给定位置插入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建以下XML元素(以自定义图形编号格式):

I'd like to build the following XML element (in order to customize figure number formatting):

<figcaption>
<span class="fignum">Figura 1.2</span> - Description of figure.
</figcaption>

但是我不知道如何指定文本的位置.实际上,如果我在创建文本之前先创建子元素,

but I don't know how to specify position of text. In fact, if I create the subelement before creating text,

import lxml.etree as et
fc = et.Element("figcaption")
fn = et.SubElement(fc, "span", {'class':'fignum'})
fn.text = "Figure 1.2"
fc.text = " - Description of figure."

我得到了不想要的结果(文本位于子元素之前):

I get an undesired result (text is positioned before subelement):

<figcaption>
 - Description of figure.<span class="fignum">Figure 1.2</span>
</figcaption>

如何指定文本相对于子元素的位置?

How can I specify position of text relatively to subelements?

推荐答案

您需要使用span元素的tail属性:

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><span class="fignum">Figure 1.2</span> - Description of figure.</figcaption>'

使用ElementTree,元素在元素内部具有text,在元素之后和外部具有tail.

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

有多个子代,父代的text是第一个子代之前的文本,元素内的所有其他文本将分配给子代的tail.

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

这篇关于Python lxml:在相对于子元素的给定位置插入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆