xml.dom.minidom for Building XML Document

This section provides a tutorial example on how to build a new XML document with Python xml.dom.minidom package.

xml.dom.minidom sub-package offers the following functionalities to build new XML documents a DOM object tree.

Here is an example Python script that builds a new XML document using the xml.dom.minidom sub-package:

#- minidom_Build_XML.py
#- Copyright (c) 2018 HerongYang.com. All Rights Reserved.
import xml.dom.minidom

#- Create new XML document with its root element
doc = xml.dom.minidom.parseString("<dictionary/>")
root = doc.documentElement

#- Create new element
word = doc.createElement("word")

#- Add new element to root

#- Create new element with an attribute
first = doc.createElement("update")
first.setAttribute("date", "2100-01-01")

#- Add new element to "word"

#- Add second element to "word"
second = doc.createElement("name")
text = doc.createTextNode("DTD")

#- Add third element to "word"
third = doc.createElement("definition")
third.appendChild(doc.createTextNode("Document Type Definition"))

#- Print out the document as pretty XML

If you run minidom_Build_XML.py, you will get:

herong> python minidom_Build_XML.py

<?xml version="1.0"?>
      <update date="2100-01-01"/>
      <name is_acronym="true">DTD</name>
      <definition>Document Type Definition</definition>

Table of Contents

 About This Book

 Introduction of XML (eXtensible Markup Language)

 XML File Syntax

 XML File Browsers

 XML-JSON Document Conversion

 DOM (Document Object Model) Programming Interface

 SAX (Simple API for XML) Programming Interface

 DTD (Document Type Definition) Introduction

 Syntaxes of DTD Statements

 Validating an XML Document against the Specified DTD Document Type

 XSD (XML Schema Definition) Introduction

 Syntaxes of XSD Statements

 Validating XML Documents Against Specified XML Schemas

 XSL (Extensible Stylesheet Language) Introduction

 Java Implementation of XSLT

 XSLT (XSL Transformations) Introduction

 XPath (XML Path) Language

 XSLT Elements as Programming Statements

 Control and Generate XML Element in the Result

 PHP Extensions for XML Manipulation

Processing XML with Python Scripts

 What Is the Python "xml" Package

xml.dom.minidom for Building XML Document

 xml.dom.minidom for Parsing XML Document

 xml.sax for Parsing XML Document

 XML Notepad - XML Editor

 XML Tools Plugin for Notepad++

 XML Plugin Packages for Atom Editor

 XML 1.1 Changes and Parsing Examples

 Archived Tutorials


 Full Version in PDF/EPUB