如果 tostring(root)
是:
<root><child1></child1><child2></child2></root>
一个人想在child1
之前插入平原(甚至可能已经逃脱(文本;在两个孩子之间;在使用lxml
的child2
之后,应该如何准确地做到这一点?我在问,因为看起来,lxml
中没有单独的文本节点,一个人只能访问Element
的text
属性,我在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>'
文本属性似乎可以完成工作。设置似乎很简单。
test="<root><child1></child1><child2></child2></root>"
from lxml import etree
root = etree.fromstring(test)
etree.tostring(root)
b'<root><child1/><child2/></root>'
print(root.text)
None
root.text = '1'
print(root.text)
1
etree.tostring(root)
b'<root>1<child1/><child2/></root>'
for child in root:
child.text = 'test'
etree.tostring(root)
b'<root>1<child1>test</child1><child2>test</child2></root>'
现在,如果元素结束后需要文本,则需要该元素的尾部属性。
for child in root:
child.text = None
child.tail = 'tail'