我有一个像这样的示例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...
最佳答案 你可以反过来说:(而不是添加一个子元素,添加一个新的父元素.)我的意思是,将根标记更改为句子,创建一个新的根元素,并将旧的根(现在的句子)插入到新根:
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>