简体   繁体   English

删除空的xml节点

[英]Removing empty xml nodes

I have an xml file that I'm trying to remove empty nodes from with python. 我有一个xml文件,试图用python删除空节点。 When I've tested it to check if a the value is, say, 'shark', it works. 当我测试它以检查a值是否为“ shark”时,它可以工作。 But when i check for it being none, it doesn't remove the empty node. 但是,当我检查是否为空时,它不会删除空节点。

for records in recordList:
        for fieldGroup in records:
            for field in fieldGroup:
                if field.text is None:
                    fieldGroup.remove(field)

is your friend here. 是您的朋友在这里。

from lxml import etree

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)

Then: 然后:

>>> print etree.tostring(doc,pretty_print=True)
<root>
  <a>1</a>
  <b>
    <c/>
  </b>
  <d/>
</root>

>>> remove_empty_elements(doc)
>>> print etree.tostring(doc,pretty_print=True)
<root>
  <a>1</a>
  <b/>
</root>

>>> remove_empty_elements(doc)
>>> print etree.tostring(doc,pretty_print=True)
<root>
  <a>1</a>
</root>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM