How to write XML declaration using xml.etree.ElementTree

后端 未结 11 956
长情又很酷
长情又很酷 2020-11-30 05:11

I am generating an XML document in Python using an ElementTree, but the tostring function doesn\'t include an XML declaration when converting to plaintext.

11条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 05:43

    If you include the encoding='utf8', you will get an XML header:

    xml.etree.ElementTree.tostring writes a XML encoding declaration with encoding='utf8'

    Sample Python code (works with Python 2 and 3):

    import xml.etree.ElementTree as ElementTree
    
    tree = ElementTree.ElementTree(
        ElementTree.fromstring('123')
    )
    root = tree.getroot()
    
    print('without:')
    print(ElementTree.tostring(root, method='xml'))
    print('')
    print('with:')
    print(ElementTree.tostring(root, encoding='utf8', method='xml'))
    

    Python 2 output:

    $ python2 example.py
    without:
    123
    
    with:
    
    123
    

    With Python 3 you will note the b prefix indicating byte literals are returned (just like with Python 2):

    $ python3 example.py
    without:
    b'123'
    
    with:
    b"\n123"
    

提交回复
热议问题