How do I wrap the contents of a SubElement in an XML tag in Python 3?

旧街凉风 提交于 2021-01-27 07:57:08

问题


I have a sample xml file like this:

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

I want to create a subelement named of , and put all the contents of into it. That is,

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

I know hot to make a subelement with ElementTree or lxml, but I have no idea of how to select from "She" to "shools." all at once.

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

回答1:


You could go about it in reverse: (Instead of adding a subelement, add a new parent.) By that I mean, change the root tag to sentence, create a new root element, and insert the old root (now sentence) into the new 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>


来源:https://stackoverflow.com/questions/14639044/how-do-i-wrap-the-contents-of-a-subelement-in-an-xml-tag-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!