Use python3.4 to parse xml files (sax, dom, and etree)

Source: Internet
Author: User

Use python3.4 to parse xml files (sax, dom, and etree)

Call the sax module to process xml files.

# Reload three methods # process xml, mainly by writing your own event processing class from xml. sax import * class DengHandler (ContentHandler): def startDocument (self): print ("---- start parsing xml document ----") def endDocument (self ): print ("---- xml file parsed ----") def startElement (self, name, attrs): if name = "author": print ("name :", attrs ['name'], "date:", attrs ["birth"]) parse ("deng. xml ", DengHandler ())

 

 

Deng. xml

 

 

 


Call the minidom In the dom module to process xml files.

 

From xml. dom. minidom import * # The scannode function prints the structure of the xml file def scannode (doc, level = 0): ret = doc. _ class __. _ name _ if doc. nodeType = Node. ELEMENT_NODE: ret + = ", Tag:" + doc. tagName print ("* 4 * level, ret) if doc. hasChildNodes: for child in doc. childNodes: scannode (child, level + 1) # ---- scannode ----- xin = parse ("book. xml ") print (xin) scannode (xin) # ---- scannode ----- x = parse (" domtest. xml ") nx = x. getElementsByTagName ("author") print (nx [0]. getAttribute ("birth") print (nx [0]. childNodes [0]. data) print (nx [1]. getAttribute ("birth") print (nx [1]. childNodes [0]. data)

 

 

Book. xml

 

 
 
  
  
   jingdong
  
  
   true
  
  
   
   
    I love python.
   
  
 

Domtest. xml

 

 

 
 
  dongdongnannan
 

 

 

Call ElementTree in the etree module to generate the required xml file.

 

import xml.etree.ElementTree as etx = et.Element("name")x.text = "dengjingdong"x.set("boy","true")sx = et.tostring(x)print(sx)


 



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.