XML Tutorials - Herong's Tutorial Examples - v5.25, by Herong Yang
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 root.appendChild(word) #- Create new element with an attribute first = doc.createElement("update") first.setAttribute("date", "2100-01-01") #- Add new element to "word" word.appendChild(first) #- Add second element to "word" second = doc.createElement("name") second.setAttribute("is_acronym","true"); text = doc.createTextNode("DTD") second.appendChild(text) word.appendChild(second) #- Add third element to "word" third = doc.createElement("definition") third.appendChild(doc.createTextNode("Document Type Definition")) word.appendChild(third) #- Print out the document as pretty XML print(doc.toprettyxml())
If you run minidom_Build_XML.py, you will get:
herong> python minidom_Build_XML.py <?xml version="1.0"?> <dictionary> <word> <update date="2100-01-01"/> <name is_acronym="true">DTD</name> <definition>Document Type Definition</definition> </word> </dictionary>
Table of Contents
Introduction of XML (eXtensible Markup Language)
DOM (Document Object Model) Programming Interface
SAX (Simple API for XML) Programming Interface
DTD (Document Type Definition) Introduction
Validating an XML Document against the Specified DTD Document Type
XSD (XML Schema Definition) Introduction
Validating XML Documents Against Specified XML Schemas
XSL (Extensible Stylesheet Language) Introduction
XSLT (XSL Transformations) Introduction
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 Tools Plugin for Notepad++
XML Plugin Packages for Atom Editor