Write XML from a string

There are two ways of writing XML from a string.

  • To an XML file[1]
    • ET.XML()
    • ET.tostring()
    • write()
  • To the memory[2]
    • ET.fromstring()

Take the xml data from [2] as an exmaple.

xmlData = """<?xml version="1.0"?>
        <data>
            <country name="Liechtenstein">
                <rank>1</rank>
                <year>2008</year>
                <gdppc>141100</gdppc>
                <neighbor name="Austria" direction="E"/>
                <neighbor name="Switzerland" direction="W"/>
            </country>
            <country name="Singapore">
                <rank>4</rank>
                <year>2011</year>
                <gdppc>59900</gdppc>
                <neighbor name="Malaysia" direction="N"/>
            </country>
            <country name="Panama">
                <rank>68</rank>
                <year>2011</year>
                <gdppc>13600</gdppc>
                <neighbor name="Costa Rica" direction="W"/>
                <neighbor name="Colombia" direction="E"/>
            </country>
        </data>"""

To an XML file

from xml.etree import ElementTree as ET

root = ET.XML(xmlData)
with open('a.xml', 'w') as f:
    f.write(ET.tostring(root).decode())

Read the xml file:

tree = ET.parse('a.xml')
rootNode = tree.getroot()
for child in rootNode:
    print(child.tag, child.attrib)
    
country {'name': 'Liechtenstein'}
country {'name': 'Singapore'}
country {'name': 'Panama'}

To the memory

root = ET.fromstring(xmlData)

Read the root directly:

for child in root:
    print(child.tag, child.attrib)
    
country {'name': 'Liechtenstein'}
country {'name': 'Singapore'}
country {'name': 'Panama'}

References

[1] https://stackoverflow.com/questions/6440115/how-do-i-parse-a-string-in-python-and-write-it-as-an-xml-to-a-new-xml-file

[2] https://docs.python.org/2/library/xml.etree.elementtree.html