gpt4 book ai didi

Python lxml : insert text at given position relatively to subelements

转载 作者:行者123 更新时间:2023-11-30 22:52:32 24 4
gpt4 key购买 nike

我想构建以下 XML 元素(为了自定义数字格式):

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

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

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."

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

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

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

最佳答案

您需要使用 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

此问题的另一个答案中的一些示例现已删除:

<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 : insert text at given position relatively to subelements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38520331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com