Tracy Ann Monteiro
Tracy Ann Monteiro

Reputation: 213

How do I write my xml output to a file

I currently have a Python script that does a get request and prints out the data which is in xml format. How do I dump this output to a xml file for parsing?

Upvotes: 3

Views: 13072

Answers (2)

rkersh
rkersh

Reputation: 4465

Assuming you have a string variable containing the xml data, you can do the following:

with open("output.xml", "w") as f:
    f.write(xmlstr)

Upvotes: 4

EdCornejo
EdCornejo

Reputation: 761

if you use Elementtree

import xml.etree.cElementTree as ET
root = ET.Element("root")
doc = ET.SubElement(root, "doc")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"

tree = ET.ElementTree(root)
tree.write("filename.xml")

Upvotes: 5

Related Questions