gpt4 book ai didi

python - 如何使用lxml在特定位置插入文本节点?

转载 作者:太空宇宙 更新时间:2023-11-03 15:10:07 24 4
gpt4 key购买 nike

如果tostring(root)类似于:

<root><child1></child1><child2></child2></root>

并且想要在 child1 之前插入纯文本(甚至可能已经转义);两个 child 之间;在使用 child2lxml 之后,应该如何准确地做到这一点?我问,因为看起来,lxml 中没有单独的文本节点,只能访问 Elementtext 属性>,而且我在API文档中也找不到任何解决方案...

无论如何,期望的最终结果将如下所示:

<root>text1<child1></child1>text2<child2></child2>text3</root>

最佳答案

要在节点的任何子节点之前插入文本,请使用节点的 text 属性。

要在节点的子节点之后插入文本,请使用该子节点的 tail 属性。

from lxml import etree
s = "<root><child1></child1><child2></child2></root>"
root = etree.XML(s)
root.text = "text1"
child1, child2 = root.getchildren()
child1.tail = "text2"
child2.tail = "text3"
print(etree.tostring(root, method="c14n")) #use this method to prevent self-closing tags in output

结果:

b'<root>text1<child1></child1>text2<child2></child2>text3</root>'

关于python - 如何使用lxml在特定位置插入文本节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44286324/

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