如何在 Python 中通过删除空格来压缩 XML 数据
使用以下函数在 Python 中通过删除空格来压缩 XML 数据:
compress_xml.py
from lxml import etree
def compress_xml_whitespace(input_bytes: io.BytesIO) -> io.BytesIO:
"""
Compresses the whitespace in an XML file.
Args:
input_bytes (io.BytesIO): The input BytesIO object containing the XML content.
Returns:
io.BytesIO: The output BytesIO object containing the compressed XML content.
"""
input_bytes.seek(0) # Reset the position to the beginning of the BytesIO object
parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse(input_bytes, parser)
# Convert the XML tree to a string without pretty printing (no newlines or indentation)
compressed_xml = etree.tostring(tree, pretty_print=False, encoding='utf-8')
# Write the compressed XML to the BytesIO output
output_bytesio = io.BytesIO(compressed_xml)
# Reset the pointer of the output BytesIO to the beginning
output_bytesio.seek(0)
return output_bytesioCheck out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow