QLands
QLands

Reputation: 2586

create a xml in python having <?xml version="xxx"?>?

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.

Upvotes: 0

Views: 843

Answers (1)

falsetru
falsetru

Reputation: 369114

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.

Upvotes: 3

Related Questions