首页 > 解决方案 > 如何删除 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。

标签: pythonpython-3.xxmllxmlelementtree

解决方案


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.


推荐阅读