使用xml.etree.ElementTree为子标签追加父包裹标签并保留原有内容
问题原因
你现有代码的问题是使用etree.SubElement(b, 'c')创建了一个全新的空<c>标签,和原有携带text2的<c>标签无关联,自然无法保留原有内容、属性以及嵌套结构。
实现步骤
要实现包裹原有标签的效果,只需要按以下逻辑操作即可:
- 找到需要被包裹的原有
<c>标签,先记录它在父节点<a>中的位置 - 把原有
<c>标签从父节点<a>中移除 - 新建父标签
new_parent_tag_added,将原有<c>标签插入到新父标签下 - 把新父标签插回到
<a>中原有<c>的位置,保证标签顺序不变
完整可运行代码
import xml.etree.ElementTree as etree XML_STRING = """ <a> <b>text1</b> <c>text2</c> </a> """ # 解析XML document_root = etree.ElementTree(etree.fromstring(XML_STRING)) root = document_root.getroot() # 找到原有c标签 old_c = root.find('c') # 记录c标签在父节点中的索引,用于后续插入保持顺序 c_index = list(root).index(old_c) # 从根节点移除原有c标签 root.remove(old_c) # 新建父标签 new_parent = etree.Element('new_parent_tag_added') # 将原有c标签加入新父节点 new_parent.append(old_c) # 将新父节点插入到原c标签的位置 root.insert(c_index, new_parent) # 美化输出(Python3.9及以上版本支持indent方法) etree.indent(root, space=" ") print(etree.tostring(root, encoding='unicode'))
运行后输出的内容和你期望的结构完全一致,且原有<c>标签的所有内容、属性都会完整保留,不用单独处理。
内容的提问来源于stack exchange,提问作者user1591156
相关产品推荐
相关产品推荐

