2013-02-01 20 views
4

我有一個示例XML文件是這樣的:如何在Python 3中將元素的內容包裝到XML標記中?

<root> 
    She 
    <opt>went</opt> 
    <opt>didn't go</opt> 
    to school. 
</root> 

我想創建一個命名的子元素,並把所有的內容進去。也就是說,

<root> 
    <sentence> 
     She 
     <opt>went</opt> 
     <opt>didn't go</opt> 
     to school. 
    </sentence> 
</root> 

我知道熱,以與ElementTree的或LXML一個子元素,但我不知道該怎樣從「她」選擇主意「shools。」一次全部。

import lxml.etree as ET 
ET.SubElement(root, 'sentence') 
I'm lost... 

回答

2

你可以去一下反向:(而不是增加一個子元素中,添加一個新的母公司)我的意思是,在root標籤更改爲sentence,創建一個新的root元素,然後將舊root(現sentence)納入新root

import lxml.etree as ET 

content = '''\ 
<root> 
    She 
    <opt>went</opt> 
    <opt>didn't go</opt> 
    to school. 
</root>''' 

root = ET.fromstring(content) 
root.tag = 'sentence' 
newroot = ET.Element('root') 
newroot.insert(0,root) 
print(ET.tostring(newroot)) 

# <root><sentence> 
# She 
# <opt>went</opt> 
# <opt>didn't go</opt> 
# to school. 
# </sentence></root> 
相關問題