Using minidom to read and write xml in Python

Source: Internet
Author: User
This article describes how to use minidom to read and write xml in Python. The example shows how to use the minidom module to operate XML files, for more information about how to use minidom to read and write xml, see the example in this article. 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)

<?xml version="1.0" encoding="UTF-8" ?> 
    
      
   
    l inux 
       30   
    
      
   
    windows 
       20   
   
 

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

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

def TestMiniDom():   from xml.dom import minidom   doc = minidom.parse( "employees.xml" )   # get root element: 
    root = doc.documentElement   # get all children elements: 
  
    employees = root.getElementsByTagName( "employee" )   for employee in employees:     print ( " ------------------------------------------- " )     # element name : employee     print (employee.nodeName)     # element xml content : 
 
  
   windows
  20
      # 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:

def CreateXml():   import xml.dom.minidom   impl = xml.dom.minidom.getDOMImplementation()   dom = impl.createDocument(None, 'employees' , None)   root = dom.documentElement    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( 'employees2.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 (<? Xml version = "1.0" encoding = "UTF-8"?> ).

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.