Using minidom to read and write xml in Python

Source: Internet
Author: User
Tags xml example

Using minidom to read and write xml in Python

This example describes how to read and write xml using minidom in Python. Share it with you for your reference. The specific analysis is as follows:

1. xml support provided by python

Two Industrial-standard xml parsing methods-SAX and DOM. SAX (simple API for XML) is based on event processing. When an XML document is read in sequence, each time an element is encountered, the corresponding event processing function is triggered for processing. DOM (Document Object Model): constructs a tree structure to express the entire xml Document. Once a tree is built, you can use the DOM interface to traverse the tree and extract the corresponding data.

Python also provides python's unique xml parsing method, which is easier to use and faster than SAX and DOM. This method is ElementTree.

The xml module of python is:

1) xml. dom. minidom

2) xml. elementtree

3) xml. sax + xml. dom

2. xml example: (employees. xml)

?

1

2

3

4

5

6

7

8

9

10

11

<? Xml version = "1.0" encoding = "UTF-8"?>

<Employees>

<Employee>

<Name> l inux </name>

<Age> 30 </age>

</Employee>

<Employee>

<Name> windows </name>

<Age> 20 </age>

</Employee>

</Employees>

3. Use xml. dom. minidom to read and write xml

1) use xml. dom. minidom to parse xml:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

Def TestMiniDom ():

From xml. dom import minidom

Doc = minidom. parse ("employees. xml ")

# Get root element: <employees/>

Root = doc.doc umentElement

# Get all children elements: <employee/>

Employees = root. getElementsByTagName ("employee ")

For employee in employees:

Print ("-------------------------------------------")

# Element name: employee

Print (employee. nodeName)

# Element xml content: <employee> <name> windows </name> <age> 20 </age> </employee>

# Basically equal to toprettyxml function

Print (employee. toxml ())

NameNode = employee. getElementsByTagName ("name") [0]

Print (nameNode. childNodes)

Print (nameNode. nodeName + ":" + nameNode. childNodes [0]. nodeValue)

AgeNode = employee. getElementsByTagName ("age") [0]

Print (ageNode. childNodes)

Print (ageNode. nodeName + ":" + ageNode. childNodes [0]. nodeValue)

Print ("-------------------------------------------")

For n in employee. childNodes:

Print (n)

TestMiniDom ()

2) use xml. dom. minidom to generate xml:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

Def CreateXml ():

Import xml. dom. minidom

Impl = xml. dom. minidom. getDOMImplementation ()

Dom = impl. createDocument (None, 'ployees', None)

Root = dom.doc umentElement

Employee = dom. createElement ('Employee ')

Root. appendChild (employee)

NameE = dom. createElement ('name ')

NameT = dom. createTextNode ('linux ')

NameE. appendChild (nameT)

Employee. appendChild (nameE)

AgeE = dom. createElement ('age ')

AgeT = dom. createTextNode ('30 ')

AgeE. appendChild (ageT)

Employee. appendChild (ageE)

F = open ('ployees2. xml', 'w ')

Dom. writexml (f, addindent = '', newl = '\ n', encoding = 'utf-8 ')

F. close ()

CreateXml ()

3) Notes for using xml. dom. minidom

* Use parse () or createDocument () to return a DOM object;

* Use the documentElement attribute of DOM to obtain the Root Element;

* DOM is a tree structure and contains many nodes. element is a node and can contain sub-elements. textNode is also a node and is the final sub-node;

* Each node has the nodeName, nodeValue, and nodeType attributes. nodeValue is the node value and is only valid for textNode. For textNode, you can use the. data Attribute to retrieve its text content.

* NodeType is the node type. The following types are available:

'Attribute _ node' 'cdata _ SECTION_NODE ''comment _ node' 'document _ FRAGMENT_NODE'

'Document _ node''' DOCUMENT _ TYPE_NODE ''' ELEMENT _ node''' ENTITY _ REFERENCE_NODE'

'Notation _ node' 'processing _ INSTRUCTION_NODE ''text _ node'

* GetElementsByTagName () can be used to find the child elements by name;

* ChildNodes returns all subnodes. All texts are textnodes, And the '\ n \ R' and spaces between elements are textnodes;

* When writexml () is used, addindent = ''indicates the indentation of child elements, and newl = '\ n' indicates the line feed between elements, encoding = 'utf-8' indicates the encoding format () of the generated xml ().

I hope this article will help you with Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.