[Python] Preserve line breaks in XML attributes when parsing with lxml

Discussão em 'Python' iniciado por Stack, Maio 22, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to batch-process a couple of XML files through a python script, with the XML files having line breaks in some of their attributes like so:

    <?xml version='1.0' encoding='UTF-8'?>
    <xml>
    <test value="This is
    a test

    with line breaks
    "/>
    </xml>


    However, I noticed that line breaks within attributes are removed when parsing this file. For example, the following script:

    import lxml.etree as ET

    with open("input.xml", "r", encoding="utf-8") as f:
    source = ET.parse(f)
    root = source.getroot()
    dest = ET.ElementTree(root)
    dest.write("output.xml", encoding="utf-8", xml_declaration=True)


    would produce the following output file:

    <?xml version='1.0' encoding='UTF-8'?>
    <xml>
    <test value="This is a test with line breaks "/>
    </xml>


    While this seems to be in line with W3Cs recommendations as per this related answer, is there a way to use xml.etree or lxml.etree for modifying the XML file without removing those line breaks?

    Continue reading...

Compartilhe esta Página