问题
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