Python Library xml.dom.minidom Howto (5)


SUMMARY (ADD ELEMENT AND TEXT NODE, SET ATTRIBUTE)

In this post, we will use what are learned from previous posts ([1], [2], [3], [4]) and give a summarized example.

Run code on repl.it

minidom-howto-5.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
#!/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)

  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)

  print(dom.toxml())

if __name__ == '__main__':
  main()

This example is quite self-explanatory. The following is the output:

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

In next post [6], we will show how to write the DOM tree into a file with XML format.


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)