#Conding:utf-8#-*-coding:utf-8-*-__author__='HDFs'"""XML parsing: Dom parsing jean the entire document is submitted to the application as a traversed object, and DOM parsing will load the document all into memory, which is not much better for large XML possibilities. """ImportPprintImportXml.dom.minidom fromXml.dom.minidomImportNodedoc=xml.dom.minidom.parse ('books.xml') Mapping={}#traversing DOM Objects forNodeinchDoc.getelementsbytagname (" Book"): #Get PropertiesIsbn=node.getattribute ('ISBN') #child NodesL=node.getelementsbytagname ('title') forNode2inchL:title="" forNode3inchNode2.childnodes:#Node.text_node: Text node, ifNode3.nodetype = =Node.TEXT_NODE:title+=Node3.data MAPPING[ISBN]=titlepprint.pprint (mapping)
Books.xml:
<Catalog> < BookISBN= "0-596-00128-2"> <title>Python&Xml</title> <title>Python&Html</title> <Date>December 2001</Date> <author>Jones, Drake</author> </ Book> < BookISBN= "0-596-15810-6"> <title>Programming Python, 4th Edition</title> <Date>October 2010</Date> <author>Lutz</author> </ Book> < BookISBN= "0-596-15806-8"> <title>Learning Python, 4th Edition</title> <Date>September 2009</Date> <author>Lutz</author> </ Book> < BookISBN= "0-596-15808-4"> <title>Python Pocket Reference, 4th Edition</title> <Date>October 2009</Date> <author>Lutz</author> </ Book> < BookISBN= "0-596-00797-3"> <title>Python Cookbook, 2nd Edition</title> <Date>March 2005</Date> <author>Martelli, Ravenscroft, Ascher</author> </ Book> < BookISBN= "0-596-10046-9"> <title>Python In a nutshell, 2nd Edition</title> <Date>July 2006</Date> <author>Martelli</author> </ Book> <!--plus many more Python books this should appear here -</Catalog>
Python DOM parsing xml