Du bist hier: Snippet-Verzeichnis » Python (121)
Sprache:

A XML file hash generator

Sprache: English
Programmiersprache: Python
Veröffentlicht von: samon007 [nicht registriert]
Letzte Änderung: 15.05.2006
Aufrufe: 986


Beschreibung

This Snippet generates a sha hash for a given XML file...The Order of a single element is NOT important for this tool, the content is.eg.:<a> <b/> <c/></a>will produce the same hash as <a> <c/> <b/></a>the order of attributes is'n importent as well.Whitespace will be XML-conform ignored.

Code

1 import xml.dom.minidom 2 import sys 3 import sha 4 import string 5 import os.path 6 7 8 version = """\ 9 XML2Hash.py v0.1 (first release) 10 Author is Felix Meulenkamp 11 EMail him at Felix.Meulenkamp@uni-dortmund.de 12 This program is under GPL!\ 13 """ 14 usage = """\ 15 16 Usage is: 17 'python XML2Hash.py <XML-File.xml>'\ 18 """ 19 20 def getHash(nodelist): 21 hashList = [] 22 for node in nodelist: 23 if node.nodeType == node.ELEMENT_NODE: 24 #hash name 25 hashList.append(sha.new(node.tagName).hexdigest()) 26 if node.attributes != None: 27 #hash attributes 28 for i in range(node.attributes.length): 29 attStr =node.attributes.item(i).name + ":" + node.attributes.item(i).nodeValue 30 hashList.append(sha.new(attStr).hexdigest()) 31 if (node.nodeType == node.TEXT_NODE): 32 #hash all strings (if not empty) 33 nodeStr = node.nodeValue.strip() 34 if nodeStr != "": 35 hashList.append(sha.new(nodeStr).hexdigest()) 36 else: 37 #if it is'n a textNode it most be something valued 38 nodeStr = getHash(node.childNodes).strip() 39 if nodeStr != "": 40 hashList.append(sha.new(nodeStr).hexdigest()) 41 # Here comes the trick: 42 # Sort all HashValues => static order 43 hashList.sort() 44 res = "" 45 for i in hashList: 46 # concat all values 47 res += i 48 if res == "": 49 return "" 50 else: 51 #return as hash (if not empty) 52 res = sha.new(res).hexdigest() 53 return res 54 55 56 #---main--- 57 if len(sys.argv) != 2: 58 print version 59 print usage 60 sys.exit(1) 61 if os.path.isfile(sys.argv[1]): 62 try: 63 dom = xml.dom.minidom.parse(sys.argv[1]) 64 except IOError: 65 print "There was an error while parsing datas (IO specific)" 66 sys.exit(2) 67 else: 68 print getHash(dom.childNodes) 69 sys.exit(0) 70 else: 71 print " '%s' seems to be not a file!!" % sys.argv[1] 72 print usage 73 sys.exit(3)

Noch kein Kommentar vorhanden

Dieses Snippet kommentieren

Name *  

E-Mail (wird nicht angezeigt) *    

Website  

Kommentar *  

Sicherheitscode Sicherheitscode *    

RSS