Як стиснути пробіли в XML за допомогою 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>

Наступна функція Python використовує швидку XML-бібліотеку lxml для стиснення зайвих пробілів у рядку XML. Вона не стискає пробіли в текстових вузлах, лише в самій структурі XML.

compress_xml_whitespace.py
import io
from lxml import etree

def compress_xml_whitespace(input_bytes: io.BytesIO) -> io.BytesIO:
    """
    Стискає пробіли у файлі XML.
    Args:
        input_bytes (io.BytesIO): Вхідний об'єкт BytesIO, що містить вміст XML.
    Returns:
        io.BytesIO: Вихідний об'єкт BytesIO, що містить стиснутий вміст XML.
    """
    input_bytes.seek(0)  # Скидаємо позицію на початок об'єкта BytesIO

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

    # Перетворюємо дерево XML на рядок без pretty printing (без переносів рядків чи відступів)
    compressed_xml = etree.tostring(tree, pretty_print=False, encoding='utf-8')

    # Записуємо стиснутий XML у вихідний BytesIO
    output_bytesio = io.BytesIO(compressed_xml)
    # Скидаємо вказівник вихідного BytesIO на початок
    output_bytesio.seek(0)
    return output_bytesio

Демонстрація

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')

Вивід:

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>

Дивіться схожі статті за категоріями: Python Xml