Remove whitespaces in XML string

前端 未结 8 1733
我在风中等你
我在风中等你 2020-11-29 04:53

How can I remove the whitespaces and line breaks in an XML string in Python 2.6? I tried the following packages:

etree: This snippet keeps the original whitespaces:<

8条回答
  •  再見小時候
    2020-11-29 05:28

    The easiest solution is probably using lxml, where you can set a parser option to ignore white space between elements:

    >>> from lxml import etree
    >>> parser = etree.XMLParser(remove_blank_text=True)
    >>> xml_str = '''
    >>>     
    >>>     
    >>> '''
    >>> elem = etree.XML(xml_str, parser=parser)
    >>> print etree.tostring(elem)
    
    

    This will probably be enough for your needs, but some warnings to be on the safe side:

    This will just remove whitespace nodes between elements, and try not to remove whitespace nodes inside elements with mixed content:

    >>> elem = etree.XML('

    spam ham eggs

    ', parser=parser) >>> print etree.tostring(elem)

    spam ham eggs

    Leading or trailing whitespace from textnodes will not be removed. It will however still in some circumstances remove whitespace nodes from mixed content: if the parser has not encountered non-whitespace nodes at that level yet.

    >>> elem = etree.XML('

    ham eggs

    ', parser=parser) >>> print etree.tostring(elem)

    hameggs

    If you don't want that, you can use xml:space="preserve", which will be respected. Another option would be using a dtd and use etree.XMLParser(load_dtd=True), where the parser will use the dtd to determine which whitespace nodes are significant or not.

    Other than that, you will have to write your own code to remove the whitespace you don't want (iterating descendants, and where appropriate, set .text and .tail properties that contain only whitespace to None or empty string)

提交回复
热议问题