如何在Python 3中将SubElement的内容包装在XML标记中? [英] How do I wrap the contents of a SubElement in an XML tag in Python 3?

查看:56
本文介绍了如何在Python 3中将SubElement的内容包装在XML标记中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个示例XML文件,如下所示:

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>

我知道用ElementTree或lxml制作子元素很热,但是我不知道如何从她"到学校"中进行选择.全部一次.

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...

推荐答案

您可以反过来解决:(而不是添加子元素,而是添加新的父元素.)我的意思是,更改 root 标记为 sentence ,创建一个新的 root 元素,并插入旧的 root (现在为 sentence )进入新的root:

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>

这篇关于如何在Python 3中将SubElement的内容包装在XML标记中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆