2017-05-31 315 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