2016-04-05 28 views
1

我使用Python創建XML文件,我需要建立這樣如何使用Python創建xml屬性xml:id?

<element xml:id="something"/> some text 

我專門用於lcml,因爲我需要的獨特標記後一些文本的屬性,使用DOM我不能這樣做。如果這可以使用DOM,那就太好了。 我該怎麼做?

回答

0

對於添加的屬性,你應該做的:

import xml.etree.cElementTree as ET 
ET.SubElement(root,'element').set('xml:id','something') 

對於添加文字:

tree = ET.parse('country_data.xml') 
root = tree.getroot() 
for element in root.findall('element'): 
    element.text = str("some text") 
tree.write('output.xml') 

Etree documentation顯示用法。

+0

看到http://stackoverflow.com/questions/18796280/set-attribute-to-element-in-python –

+0

好,我仍然需要寫一些文字在標籤之後: texttexttext – Noro

+0

答案被編輯 –

0

您應該使用tail屬性:

etree_element.tail = ' some text'