Python Library xml.dom.minidom Howto (4)


SET ATTRIBUTE OF AN ELEMENT

In previous posts ([1], [2], [3]), we showed how to create document, add text node, create an element node and append the element node to the document element (root element) via xml.dom.minidom. In this post, we will show how to set attribute of the element node.

Run code on repl.it

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

  print(dom.toxml())

if __name__ == '__main__':
  main()

In line 11, we set the attribute of document element as integer=1. The following is the output:

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

In the next post [5], we will use what we learn from (1)~(4) and give a synthetical example.


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)