Python etree control empty tag format

前端 未结 5 1595
小蘑菇
小蘑菇 2020-12-06 10:32

When creating an XML file with Python\'s etree, if we write to the file an empty tag using SubElement, I get:


5条回答
  •  生来不讨喜
    2020-12-06 11:34

    As of Python 3.4, you can use the short_empty_elements argument for both the tostring() function and the ElementTRee.write() method:

    >>> from xml.etree import ElementTree as ET
    >>> ET.tostring(ET.fromstring(''), short_empty_elements=False)
    b''
    

    In older Python versions, (2.7 through to 3.3), as a work-around you can use the html method to write out the document:

    >>> from xml.etree import ElementTree as ET
    >>> ET.tostring(ET.fromstring(''), method='html')
    ''
    

    Both the ElementTree.write() method and the tostring() function support the method keyword argument.

    On even earlier versions of Python (2.6 and before) you can install the external ElementTree library; version 1.3 supports that keyword.

    Yes, it sounds a little weird, but the html output mostly outputs empty elements as a start and end tag. Some elements still end up as empty tag elements; specifically , ,
    and such. Still, it's that or upgrade your Fortran XML parser to actually parse standards-compliant XML!

提交回复
热议问题