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

使用ElementTree去除XML元素空白符时遭遇AttributeError问题求助

解决XML元素首尾及元素间空白清理时的AttributeError问题

你的错误根源很明确:不是所有XML元素都有text或tail属性值。比如自闭合的<neighbor/>标签,它的elem.text是None;当元素是父节点的最后一个子元素时,它的elem.tail也会是None——直接对None调用strip()自然会触发AttributeError。

修复方案很简单,先判断属性是否为None,再执行strip操作:

for elem in root.iter():
    # 清理元素文本:仅当text不为空时执行strip
    if elem.text is not None:
        elem.text = elem.text.strip()
    # 清理元素尾文本:仅当tail不为空时执行strip
    if elem.tail is not None:
        elem.tail = elem.tail.strip()

或者用更简洁的三元表达式写法,效果完全一致:

for elem in root.iter():
    elem.text = elem.text.strip() if elem.text else elem.text
    elem.tail = elem.tail.strip() if elem.tail else elem.tail

这样处理后,就能完美解决你遇到的三种空白问题:

  • Liechtenstein的description末尾多余空白被清除
  • Singapore的neighbor与description之间的空白(属于neighbor的tail)被清除
  • Panama的description开头多余空白被清除

处理后的XML会变成:

<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
<description>Liechtenstein has a lot of flowers.</description>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
<description>Singapore has a lot of street markets.</description>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
<description>Panama has a lot of great food.</description>
</country>
</data>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 23:39:08