2013-10-23 102 views
2
關閉和打開元素
root = etree.Element('document') 
rootTree = etree.ElementTree(root) 
firstChild = etree.SubElement(root, 'test') 

輸出是:覆蓋LXML行爲編寫空標籤

<document> 
<test/> 
</document 

我所要的輸出是:

<document> 
<test> 
</test> 
</document> 

我知道兩者是等價的,但有沒有辦法獲得我想要的輸出。

回答

3

這裏是你如何能做到這:

from lxml import etree 

root = etree.Element('document') 
rootTree = etree.ElementTree(root) 
firstChild = etree.SubElement(root, 'test') 

print etree.tostring(root, pretty_print=True) 

# Set empty string as element content to force open and close tags 
firstChild.text = '' 

print etree.tostring(root, pretty_print=True) 

輸出:

<document> 
    <test/> 
</document> 

<document> 
    <test></test> 
</document>