Python Library xml.dom.minidom Howto (3)


ADD AN ELEMENT

In previous posts ([1] and [2]), we showed how to create a document and add a text node to the root document via xml.dom.minidom. In this post, we will show how to create a new element node and add it to the DOM tree.

Run code on repl.it

minidom-howto-3.py | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#!/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)

  root = dom.documentElement
  demoNode = dom.createElement(u'demoTag')
  root.appendChild(demoNode)

  print(dom.toxml())

if __name__ == '__main__':
  main()

In line 11 and 12, we create a node with the tag demoTag and add it to the root element of the document. The following is the output:

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

In the next post [4], we will show how to set the attribute of the 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)