Call the Sax module to process the XML file.
#重载了三个方法 # Processing XML, mainly to write its own event processing class from Xml.sax import *class Denghandler (ContentHandler): def startdocument (self): print ("----Start parsing XML document----") def enddocument (self): print ("----parsing of XML documents----") def startelement ( SELF,NAME,ATTRS): if name = = "Author": Print ("Name:", attrs[' name '], "date:", attrs["Birth"]) parse ("Deng.xml", Denghandler ())
Deng.xml
<?xml Version = "1.0" encoding = "Utf-8"? ><author name = "Dengjingdong" birth = "19920517" ></author>< /people>
Call Minidom in the DOM module to process the XML file.
From xml.dom.minidom Import * #scannode函数打印xml文件的结构def scannode (doc,level = 0): ret = doc.__class__.__name__ If Doc.nodetype = = Node.element_node: ret + = ", Label:" + 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
<?xml Version = "1.0" encoding = "Utf-8"? ><book><title>the book Title</title><author> <name>jingdong</name><boy>true</boy></author><chapter number = "1" ><title > First chapter </title><para>i Love python.</para></chapter></book>
Domtest.xml
<?xml Version = "1.0" encoding = "Utf-8"? ><people><author name = "Dengjingdong" birth = "1990517" >dongd Ong</author><author name = "Wushengnan" birth = "19920520" >nannan</author></people>
Call the 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)
parsing XML files using python3.4 (sax, DOM, etree)