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)