skip to main | skip to sidebar

Python Programs and Examples

Pages

  • Home
 
  • RSS
  • Facebook
  • Twitter
Sunday, October 21, 2012

Python XML Parser

Posted by Raju Gupta at 5:30 PM – 0 comments
 

In our project we had kept the operations rules as an XML and the below mentioned parser was used to get the conditions to be applied for each operation.

The xml.dom.minidom was used to parse the xml file and return a document object .The document object was used to obtain the child nodes and for each child nodes the corresponding fileds and attributes were retrieved using the get attribute method and appended as a tuple.
The tuple was then included in the dictionary with the nodename as the key.



 import xml.dom.minidom

class XMLParser:
    def __init__(self, filePath):
        self.xml_file_path = filePath

    def get_a_document(self):
        return xml.dom.minidom.parse(self.xml_file_path)

    def process_xml_return_dict(self):
        doc = self.get_a_document()
        fieldMapping = doc.childNodes[0]
        operations = {}
        for layer in fieldMapping.childNodes:
            if layer.nodeType == xml.dom.minidom.Node.TEXT_NODE or layer.nodeType == xml.dom.minidom.Node.COMMENT_NODE:
                continue
            fieldList = self.get_fields(layer)
            attrList = self.get_attributes(layer)
            operations[layer.nodeName] = (attrList, fieldList)
        return operations

    def get_attributes(self, node):
        attrList = []
        nodeMap = node.attributes
        for index in range(nodeMap.length):
            attrName = nodeMap.item(index).name
            attrValue = node.getAttribute(attrName)
            attrList.append((attrName, attrValue))
        return attrList

    def get_fields(self, node):
        fieldList = []
        for childNode in node.childNodes:
            if childNode.nodeType != xml.dom.minidom.Node.TEXT_NODE and childNode.nodeType != xml.dom.minidom.Node.COMMENT_NODE:
                fromField = childNode.getAttribute('FromField')
                toField = childNode.getAttribute('ToField')
                fieldValue = childNode.getAttribute('Value')
                condition = childNode.getAttribute('Condition')
                fieldList.append((fromField, toField, fieldValue, condition))
        return fieldList
Python pickle module & Zip file creation
 
Description
The solution gives a solution to use the pickle module and to create a Zip File.  
 
 # below is a typical Python dictionary object of roman numerals
 romanD1 = {'I':1,'II':2,'III':3,'IV':4,'V':5,'VI':6,'VII':7,'VIII':8,'IX':9,'X':10}
  
 # to save a Python object like a dictionary to a file
 # and load it back intact you have to use the pickle module
 import pickle
 print "The original dictionary:"
 print romanD1
 file = open("roman1.dat", "w")
 pickle.dump(romanD1, file)
 file.close()
 # now load the dictionay object back from the file ...
 file = open("roman1.dat", "r")
 romanD2 = pickle.load(file)
 file.close()
 print "Dictionary after pickle.dump() and pickle.load():"
 print romanD2

 # for large text files you can write and read a zipped file (PKZIP format)
 # notice that the syntax is mildly different from normal file read/write
 import zipfile
 zfilename = "English101.zip"
 zout = zipfile.ZipFile(zfilename, "w")
 zout.writestr(zfilename, str1 + str2)
 zout.close()
 # read the zipped file back in
 zin = zipfile.ZipFile(zfilename, "r")
 strz = zin.read(zfilename)
 zin.close()
 print "Testing the contents of %s:" % zfilename
 print strz

Labels: Python XML Parser Email This BlogThis! Share to X Share to Facebook

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments (Atom)
  • Popular
  • Recent
  • Archives

Popular Posts

  • To Send the entire contents of directory as an email Message.
    Here is a Python Program to send the entire contents of a directory as an email message #!/usr/bin/env python """Send the...
  • Control Structures in Python
    This Program explains different control structures in python If ==== # basic "If" if boolean: x = 1 else: x = 0 # No...
  • Python Code for creating Screen saver
    This is the Python code for creating a screensaver of a moving ball. The ball will bee moving along the screen and when it hits any of the ...
  • Python script for walking the directory tree structure but excluding some directories and files
    The script walks the directory structure recursively. Some of the directories and files can be excluded from the walk by providing them in ...
  • XML to CSV Converter
    Python Program to extract each execution data (few children in xml) and create a csv file. def xml2csv(inputFile,outputFile,elemName,n...
  • HTML Email using Python
    We created a module called sendmail which email html content. Each of application dumps data from the datastructure into html format and th...
  • Overview of Python Programming Language
    Python is an easy to learn, powerful programming language. It has efficient high level data structures and a simple but effective approac...
  • Fast and efficient Backup script that works on Windows and Linux
    This python script backup your directory structure that works on Linux and Windows both. It directly uses the shell to do this task and she...
  • Run Application from host
    import os os.execl( "c:/Windows/Notepad.exe", "c:/userlog.txt") print "Running notepad" #or import subpro...
  • Orphan Checker
    The script does not use any outside libraries, thus keeping its execution simple. we will start by initializing the arrays that we'll...
Powered by Blogger.

Archives

  • ▼  2012 (66)
    • ▼  October (28)
      • Find text/pattern under parent folder from matched...
      • XML to CSV Converter
      • XSL to CSV converter
      • Spell Corrector in Python
      • Format a plain ASCII file using Python script
      • Control Structures in Python
      • Python script to zip and unzip files
      • Fast and efficient Backup script that works on Win...
      • File Splitter Script
      • Python script for walking the directory tree struc...
      • Python XML Parser
      • IP Address Generation
      • Orphan Checker
      • HTML Email using Python
      • Python interface to load commands.
      • Python script to Validate Tabular format Data and ...
      • Python script to Load Configuration file content i...
      • Python Script to search file for specific content
      • Network Wise File Concatenation
      • Python Script for Adding or Subtracting the Dates
      • Program to create make file in VMS/UNIX
      • Python Code for creating Screen saver
      • Run Application from host
      • Multithreading in Python
      • This utility determines the size of a folder and i...
      • Using UNIX Environment Variables From Python
      • CVS Macro for Commited Files
      • Generating unique id's
    • ►  September (36)
    • ►  March (1)
    • ►  February (1)
 

Labels

  • Command Execution Using Python (2)
  • Control Structure (1)
  • CSV Examples (4)
  • Database (3)
  • Features of Python Programming Language (1)
  • File Example (2)
  • IF Statement (1)
  • List (2)
  • Mail (5)
  • Multithreading (1)
  • MySQL (3)
  • Python Date Example (2)
  • Python Example (2)
  • Python File Example (7)
  • Python Introduction (1)
  • Python Network Example (1)
  • Python XML Parser (2)
  • Searching Example (2)
  • Simple Calculation Program (1)
  • Strings (4)
  • Zip File Example (1)

Followers

 
 
© 2011 Python Programs and Examples | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger