0

There are plenty of examples in the web on how to create a xml with python. An examples is:

import elementtree.ElementTree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "doc")

field1 = ET.SubElement(doc, "field1")
field1.set("name", "blah")
field1.text = "some value1"

field2 = ET.SubElement(doc, "field2")
field2.set("name", "asdfasd")
field2.text = "some vlaue2"

tree = ET.ElementTree(root)

tree.write("filename.xml")

But this creates a document starting with

<root> 

and not with

<?xml version="xxx"?> 

How can I add the

<?xml version="xxx"?>

bit to the XML?

Thanks, Carlos.

1

1 Answer 1

3

Specify xml_declaration and encoding:

tree.write("filename.xml", xml_declaration=True, encoding='utf-8')

According to ElementTree.write documentation:

write(file, encoding="us-ascii", xml_declaration=None, default_namespace=None, method="xml")

Writes the element tree to a file, as XML. file is a file name, or a file object opened for writing. encoding is the output encoding (default is US-ASCII). xml_declaration controls if an XML declaration should be added to the file. Use False for never, True for always, None for only if not US-ASCII or UTF-8 (default is None). default_namespace sets the default XML namespace (for “xmlns”). method is either "xml", "html" or "text" (default is "xml"). Returns an encoded string.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.