Python Library xml.dom.minidom Howto (6)


WRITE XML/HTML TO FILE

In previous posts ([1], [2], [3], [4], [5]), we show how to generate XML/HTML content using Python xml.dom.minidom. Here we will show how to write the content into a file. The following is the code:

minidom-howto-6.py | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import xml.dom.minidom
import codecs

def main():
  impl = xml.dom.minidom.getDOMImplementation()
  dom = impl.createDocument(None, u'html', None)

  demoNode = dom.createElement(u'demoTag')
  demoNode.setAttribute(u'integer', u'1')
  demoTextNode = dom.createTextNode(u'Hello World!')
  demoNode.appendChild(demoTextNode)

  root = dom.documentElement
  root.appendChild(demoNode)

  f = file('example.xml', 'wb')
  writer = codecs.lookup('utf-8')[3](f)
  dom.writexml(writer, encoding = 'utf-8')
  f.close()

if __name__ == '__main__':
  main()

The trick here is in line 5, and lines 19, 20, 21, 22. The library codecs must be imported to encode the XML file. The lines 19, 20, 21, 22 perform the task of writing the XML content into a file. It's pretty simple and easy. This again shows the power and beauty of Python.

In final post [7], we will show how to read a XML file and parse the content.


Python Library xml.dom.minidom Howto series:

[1]Python Library xml.dom.minidom Howto (1)
[2]Python Library xml.dom.minidom Howto (2)
[3]Python Library xml.dom.minidom Howto (3)
[4]Python Library xml.dom.minidom Howto (4)
[5]Python Library xml.dom.minidom Howto (5)
[6]Python Library xml.dom.minidom Howto (6)
[7]Python Library xml.dom.minidom Howto (7)