在给定的Python元素相对位置插入

2024-09-28 22:33:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

^{pr2}$

我得到了一个不期望的结果(文本位于子元素之前):

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

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


Tags: of文本元素格式descriptionxmlclassfigure
1条回答
网友
1楼 · 发布于 2024-09-28 22:33:38

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

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。在

对于多个子元素,父元素的text是第一个子元素之前的文本,元素中的所有其他文本都将分配给子元素tail。在

这个问题的另一个答案中的一些例子已被删除:

^{pr2}$

相关问题 更多 >