pythonpython-3.xxmlelementtreexml-declaration

Python code that creates XML insert header


I have a similar code to generate a XML. THe code is similar to this:

import xml.etree.ElementTree as ET
import requests
import json
import csv

data = ET.Element('XMLFORMPOST')

element0 = ET.SubElement(data, 'REQUEST')
element1 = ET.SubElement(data, 'LOGIN')
element2 = ET.SubElement(data, 'PARTNUM')
element2.text = str(ingramPartNumber)
element3 = ET.SubElement(data, 'LOOKUPTYPE')

b_xml = ET.tostring(data)
 with open("finalfile.xml", "wb") as f:
    f.write(b_xml)

I want in the final XML to have the header as shown here

<?xml version='1.0' encoding='utf8'?>

After hat header the rest of the elements. Something as this:

<?xml version='1.0' encoding='utf8'?>
<outer><inner>1</inner></outer>

I know that something as “xml_declaration=True” can do the job but I don;t know how to apply or if there is any other solution to do so.

How can I modify the “with open” commando or do something else to add the header with this script?


Solution

  • You should use the write method of ElementTree as stated, write(f, encoding='utf-8', xml_declaration=True).

    Your code would look something like this:

    import xml.etree.ElementTree as ET
    
    data = ET.Element('XMLFORMPOST')
    
    element0 = ET.SubElement(data, 'REQUEST')
    element1 = ET.SubElement(data, 'LOGIN')
    element2 = ET.SubElement(data, 'PARTNUM')
    element2.text = str(ingramPartNumber)
    element3 = ET.SubElement(data, 'LOOKUPTYPE')
    
    xml_doc = ET.ElementTree(element=data)
    with open("finalfile.xml", "wb") as f:
        xml_doc.write(f, encoding='utf-8', xml_declaration=True)