5

I'm slightly confused about writing an xml file using the xml ElementTree module. I tried to build the document: e.g.

a = ET.Element('a')
b = ET.SubElement(a, 'b')
c = ET.SubElement(a, 'c')
d = ET.SubElement(c, 'd')

How do I exactly take this, and write it to a file?

2 Answers 2

5

Create an instance of ElementTree class and call write():

class xml.etree.ElementTree.ElementTree(element=None, file=None)

ElementTree wrapper class. This class represents an entire element hierarchy, and adds some extra support for serialization to and from standard XML.

element is the root element. The tree is initialized with the contents of the XML file if given.

tree = ET.ElementTree(a)
tree.write("output.xml")
Sign up to request clarification or add additional context in comments.

2 Comments

Just to make sure I'm doing this correctly. If I wanted to attach a value or variable to a tag would it be: b.attrib = value , b.tag = variable?
@Shan I think you mean the text of an element. In this case, it should be e.g. d.text = "test".
2

You can write xml using ElementTree.write() function -

import xml.etree.ElementTree as ET
a = ET.Element('a')
b = ET.SubElement(a, 'b')
c = ET.SubElement(a, 'c')
d = ET.SubElement(c, 'd')
ET.ElementTree(a).write("test.xml")

This would write to file - test.xml -

<a><b /><c><d /></c></a>

To write xml with indents and elements on newline , you can use - xml.dom.minidom.toprettyxml . Example -

import xml.etree.ElementTree as ET
import xml.dom.minidom as md
a = ET.Element('a')
b = ET.SubElement(a, 'b')
c = ET.SubElement(a, 'c')
d = ET.SubElement(c, 'd')
xmlstr = ET.tostring(a).decode()
newxml = md.parse(xmlstr)
newxml = md.parseString(xmlstr)
with open('test.xml','w') as outfile:
    outfile.write(newxml.toprettyxml(indent='\t',newl='\n'))

Now, test.xml would look like -

<?xml version="1.0" ?>
<a>
    <b/>
    <c>
        <d/>
    </c>
</a>

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.