2017-05-31 324 views
0

如果tostring(root)是一样的东西:如何使用lxml在特定位置插入文本节点?

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

和一个要插入平原,(甚至已逃走)文本child1前;两个孩子之间; child2lxml之后,应该怎么做呢?我在问,因为看起来像lxml中没有单独的文本节点,只能访问Elementtext属性,并且我在API文档中找不到任何解决方案...

无论如何,所需的最终结果会是这个样子:

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

'xml.etree.ElementTree'解决方案如何? – RomanPerekhrest

+0

..等等,为什么'-1'? –

+0

@RomanPerekhrest你会关心那一个吗? –

回答

1

要在节点的任何孩子之前插入文本,使用该节点的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>' 
0

文本属性似乎做的工作。设置它似乎很简单。

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' 
+0

但他希望将第二个和第三个字符串放在child1和child2标签的外侧。 – Kevin

+0

然后他需要使用文本和尾巴的组合。下面的答案正确,我想 – BoboDarph