Como comprimir whitespace en XML usando Python

compressed_xml_output.xml
<root><parent><child><subchild>   This is some text with    irregular   spacing.   </subchild><subchild>Another piece of text with\n                newlines and     tabs.</subchild></child><child><subchild>Text with\n                multiple\n                lines.</subchild><subchild>   Leading and trailing spaces   </subchild></child></parent><parent><child><subchild>Mixed    whitespace    types.</subchild><subchild>   </subchild></child></parent></root>

La siguiente funcion de Python usara la libreria XML rapida lxml para comprimir whitespace innecesario en un string XML. No comprimira whitespace en nodos de texto, solo en la estructura XML misma.

compress_xml_whitespace.py
import io
from lxml import etree

def compress_xml_whitespace(input_bytes: io.BytesIO) -> io.BytesIO:
    """
    Comprime el whitespace en un archivo XML.
    Args:
        input_bytes (io.BytesIO): El objeto BytesIO de entrada que contiene el contenido XML.
    Returns:
        io.BytesIO: El objeto BytesIO de salida que contiene el contenido XML comprimido.
    """
    input_bytes.seek(0)  # Resetear la posicion al inicio del objeto BytesIO

    parser = etree.XMLParser(remove_blank_text=True)
    tree = etree.parse(input_bytes, parser)

    # Convertir el arbol XML a un string sin pretty printing (sin newlines o indentacion)
    compressed_xml = etree.tostring(tree, pretty_print=False, encoding='utf-8')

    # Escribir el XML comprimido al output BytesIO
    output_bytesio = io.BytesIO(compressed_xml)
    # Resetear el puntero del output BytesIO al inicio
    output_bytesio.seek(0)
    return output_bytesio

Demostracion

compress_xml_whitespace_demo.py
test_xml = """<root>
    <parent>
        <child>
            <subchild>   This is some text with    irregular   spacing.   </subchild>
            <subchild>Another piece of text with
                newlines and     tabs.</subchild>
        </child>
        <child>
            <subchild>Text with
                multiple
                lines.</subchild>
            <subchild>   Leading and trailing spaces   </subchild>
        </child>
    </parent>
    <parent>
        <child>
            <subchild>Mixed    whitespace    types.</subchild>
            <subchild>   </subchild>
        </child>
    </parent>
</root>"""

test_xml_bytesio = io.BytesIO(test_xml.encode('utf-8'))

compress_xml_whitespace(test_xml_bytesio).read().decode('utf-8')

Salida:

output.txt
<root><parent><child><subchild>   This is some text with    irregular   spacing.   </subchild><subchild>Another piece of text with\n                newlines and     tabs.</subchild></child><child><subchild>Text with\n                multiple\n                lines.</subchild><subchild>   Leading and trailing spaces   </subchild></child></parent><parent><child><subchild>Mixed    whitespace    types.</subchild><subchild>   </subchild></child></parent></root>

Echa un vistazo a artículos similares por categoría: Python Xml