You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup操作XML时,如何正确添加自定义标签避免转义?

解决BeautifulSoup添加XML标签字符串时的转义问题

直接用append()添加字符串形式的XML标签时,BeautifulSoup会把内容当成纯文本处理,自动转义<、>等特殊字符——哪怕用html.unescape()处理字符串,append时还是会被重新转义,这就是你看到&lt;和&gt;的原因。

要正确添加XML标签,需要把字符串转换成BeautifulSoup的Tag对象,或者直接构造标签,两种方法都能解决问题:

方法1:解析字符串生成Tag对象

先把包含标签的字符串用BeautifulSoup解析成XML结构,提取出对应的标签再添加:

from bs4 import BeautifulSoup

# 你的原始转义字符串
no_email_str = '&lt;errorEmailNotification enabled=&quot;false&quot;/&gt;'
# 解析字符串生成标签对象
tag_soup = BeautifulSoup(no_email_str, "xml")
no_email_tag = tag_soup.find("errorEmailNotification")

# 处理目标XML
bs = BeautifulSoup(xml, "xml")
header = bs.find("S:Header")
# 添加标签对象而非字符串
header.append(no_email_tag)
print(header.prettify())

方法2:直接构造新标签

如果不需要从字符串读取标签,直接用new_tag()方法创建标签并设置属性更高效:

from bs4 import BeautifulSoup

bs = BeautifulSoup(xml, "xml")
header = bs.find("S:Header")
# 创建新标签
no_email_tag = bs.new_tag("errorEmailNotification")
# 设置标签属性
no_email_tag["enabled"] = "false"
# 添加到目标节点下
header.append(no_email_tag)
print(header.prettify())

两种方法都能得到你期望的输出:

<S:Header>
 <Some Header info/>
 <errorEmailNotification enabled="false"/>
</S:Header>

内容的提问来源于stack exchange,提问作者iNeedScissors61

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 21:03:38