[英]How do I wrap the contents of a SubElement in an XML tag in Python 3?
I have a sample xml file like this: 我有一个示例XML文件,如下所示:
<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." 我知道用ElementTree或lxml制作子元素很热,但是我不知道如何从“她”到“学校”中进行选择。 all at once.
一次全部。
import lxml.etree as ET
ET.SubElement(root, 'sentence')
I'm lost...
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
: 您可以相反地进行处理:(而不是添加子元素,而是添加新的父元素。)我的意思是将
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.