Python Library xml.dom.minidom Howto (1)


CREATE A DOCUMENT

Python provides a simple xml.dom.minidom library which can be used for XML/HTML manipulation. Here I want to share some of what I learned to beginners on how to manipulate XML/HTML in Python.

First, we create a document DOM with root element called html. Here is the sample code:

Run code on repl.it

minidom-howto-1.py | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import xml.dom.minidom

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

  print(dom.toxml())

if __name__ == '__main__':
  main()

In line 7 and 8, we create a dom with root element html. If you run the script, the following result will show up.

<?xml version="1.0" ?><html/>

In the next post [2], we will show how to add a text node to the root element.


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)