Python Library xml.dom.minidom Howto (2)


CREATE AND ADD A TEXT NODE

In previous post [1], we showed how to create a XML DOM, of which the root element is called html via xml.dom.minidom. In this post, we show how to add a text node to the root element. Note that the text node is the leaf in the DOM trees, which means the text node has no children node or element.

Run code on repl.it

minidom-howto-2.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
  demoTextNode = dom.createTextNode(u'Hello World!')
  root.appendChild(demoTextNode)

  print(dom.toxml())

if __name__ == '__main__':
  main()

In line 10, we get the root element of the document DOM. In line 11, we create a text node, and in line 12, we add the text node to the root element. Note that the text node can be added to any element, not only to root element.

The following is the output:

<?xml version="1.0" ?><html>Hello World!</html>

It's pretty easy and straight forward to manipulate the xml.dom.minidom library. In the next post [3], we will show how to create an element and add it to the DOM trees.


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)