我想清理我的xml,这样不仅它是有效的XML,而且它以一种非常人类可读的方式进行格式化.例如:
<Items>
<Name>Hello</Name>
<Cost>9.99</Cost>
<Condition/>
</Items>
Run Code Online (Sandbox Code Playgroud)
我想删除任何带有空标记的行,留下:
<Items>
<Name>Hello</Name>
<Cost>9.99</Cost>
</Items>
Run Code Online (Sandbox Code Playgroud)
我尝试使用正则表达式进行此操作,但在将其保留为可读格式方面并没有太多运气:
txt = etree.tostring(self.xml_node, pretty_print=True)
txt = re.sub(r'<[a-zA-Z]+/>\n', '', txt)
Run Code Online (Sandbox Code Playgroud)
实现上述目标的最佳方法是什么?
使用XML解析器.
我们的想法是找到所有带有//*[not(node())]XPath表达式的空节点,并将其从树中删除.示例,使用lxml:
from lxml import etree
data = """
<Items>
<Name>Hello</Name>
<Cost>9.99</Cost>
<Condition/>
</Items>
"""
root = etree.fromstring(data)
for element in root.xpath(".//*[not(node())]"):
element.getparent().remove(element)
print etree.tostring(root, pretty_print=True)
Run Code Online (Sandbox Code Playgroud)