python - 如何删除 XML 中仅包含空格的空 XML 标记?
问题描述
我需要删除这样的案例:
<text> </text>
我有在没有空格时有效的代码,但是如果有空格呢?
代码:
doc = etree.XML("""<root><a>1</a><b><c></c></b><d></d></root>""")
def remove_empty_elements(doc):
for element in doc.xpath('//*[not(node())]'):
element.getparent().remove(element)
我还需要使用 lxml 而不是 BeautifulSoup。
解决方案
This XPath,
//*[not(*)][not(normalize-space())]
will select all leaf elements with only whitespace content.
For your example specifically,
<root><a>1</a><b><c></c></b><d></d></root>
these elements will be selected: c
and d
.
For an example that also includes whitespace-only elements,
<root>
<a>1</a>
<b>
<c></c>
</b>
<d/>
<e> </e>
<f>
</f>
</root>
these elements will be selected: c
, d
, e
, and f
.
推荐阅读
- python - VS Code 交互式窗口浏览器
- sql - 如何在 Oracle SQL 中选择不同的多列值?
- spring-boot - SpringBoot Docker REST Connection Refused 即使创建了 docker-compose
- typescript - typescript 处理不同类型的返回
- sql - 如何在记事本++中的一个大sql行中将特定字符之后的某些字符替换为另一个特定字符
- laravel - 在 laravel 发布请求中找不到 404
- python - Python 3:AttributeError:从 git bash 启动时,“NoneType”对象没有属性“提示”
- android - 我可以使用 OkHTTP 将 JSON 和表单数据添加到发布请求吗?
- r - 根据案例更改数据框中的值
- flutter - 无法无条件访问属性“isEmpty”,因为接收者可以为“null”