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

如何让lxml.etree.tostring显示空节点的完整起止标签?

解决lxml输出空标签不收缩的问题

你当前的代码解析空标签后,输出会自动转为自闭合形式。要让输出保持<foo class="abc"></foo>这种成对标签的格式,只需在etree.tostring()方法中添加short_empty_elements=False参数即可。

修改后的代码如下:

from lxml import etree
tree = etree.XML('<foo class="abc"></foo>')
print(etree.tostring(tree, encoding='utf-8', short_empty_elements=False).decode('utf-8'))

执行后输出结果:

<foo class="abc"></foo>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 11:03:09