How to write XML declaration using xml.etree.ElementTree

后端 未结 11 951
长情又很酷
长情又很酷 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 06:08

    Easy

    Sample for both Python 2 and 3 (encoding parameter must be utf8):

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

    From Python 3.8 there is xml_declaration parameter for that stuff:

    New in version 3.8: The xml_declaration and default_namespace parameters.

    xml.etree.ElementTree.tostring(element, encoding="us-ascii", method="xml", *, xml_declaration=None, default_namespace=None, short_empty_elements=True) Generates a string representation of an XML element, including all subelements. element is an Element instance. encoding 1 is the output encoding (default is US-ASCII). Use encoding="unicode" to generate a Unicode string (otherwise, a bytestring is generated). method is either "xml", "html" or "text" (default is "xml"). xml_declaration, default_namespace and short_empty_elements has the same meaning as in ElementTree.write(). Returns an (optionally) encoded string containing the XML data.

    Sample for Python 3.8 and higher:

    import xml.etree.ElementTree as ElementTree
    
    tree = ElementTree.ElementTree(ElementTree.fromstring('123'))
    root = tree.getroot()
    print(ElementTree.tostring(root, encoding='unicode', method='xml', xml_declaration=True))
    

提交回复
热议问题