1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
   |  
from xml.dom.minidom import *
 
import os.path, os
import sys, getopt
 
pg_version="1.5"
 
class AttrNode:
 
	def __init__(self, name, value):
		self._name=name
		self._value=value
 
	def name(self,val=''):
		if val == '':
			return self._name
		self._name=val
 
	def value(self,val=''):
		if val == '':
			return self._value
		self._value=val
class XmlNode:
 
	def __init__(self):
		self._name=None
		self._text=None
		self.list_attr=[]
		self.list_child=[]
 
	def name(self,value=''):
		if value == '':
			return self._name
		self._name=value
 
	def text(self,value=''):
		if value == '':
			return self._text
		self._text=value
 
 
	def attr(self,name='', value=''):
		if (name == '' and value == ''):
			return self.list_attr
		if (name != '' and value == ''):
			for i in self.list_attr:
				if i.name()==name:
					return i.value
		for i in self.list_attr:
			if i.name()==name:
				return True
		self.list_attr.append(AttrNode(name,value))
 
	def child(self, name=''):
		if name == '':
			return self.list_child
		for i in self.list_child:
			if i==name:
				return True
		self.list_child.append(name)
 
class XmlDTD:
 
	def __init__(self, path):
		self._path=path
		self.list_node=[]
		self.node_racine=None
 
	def parseDTD(self):
		try:
			xmldoc = parse(self._path)
			self.node_racine=xmldoc.documentElement
			self.addNode(self.node_racine)
			self.analyseXml(self.node_racine)
		except Exception, e:
			raise e 
 
	def addNode(self, n):
		for i in self.list_node:
			if i.name() == n.nodeName:
				for j in n.attributes.keys():
					i.attr(j, n.attributes[j].value)
				for m in n.childNodes:
    					if m.nodeType == Node.ELEMENT_NODE:
						i.child(m.nodeName)
				return i			
		a=XmlNode()
		a.name(n.nodeName)
		for j in n.attributes.keys():
			a.attr(j, n.attributes[j].value)
		for m in n.childNodes:
    			if m.nodeType == Node.ELEMENT_NODE:
				a.child(m.nodeName)
    			elif m.nodeType == Node.TEXT_NODE:
				a.text(m.data)	
		self.list_node.append(a)
		return a
 
	def analyseXml(self, node):
		for n in node.childNodes:
    			if n.nodeType == Node.ELEMENT_NODE:
				a = self.addNode(n)
			self.analyseXml(n)
 
	def analyseChild(self,node_sup,node_inf):
		listenode=self.getChild(xmldoc.documentElement, node_sup, [], 0)
		print listnode
 
	def getChild(self, node, name_node, listnode, level):
		for n in node.childNodes:
    			if n.nodeType == Node.ELEMENT_NODE and n.nodeName == name_node:
				listnode.append(n)
			listnode = self.getChild(n,name_node, listnode, level+1)
		if node.nodeName == name_node:
			listnode.append(node)
		return listnode
 
 
 
	def getDTD(self):
		a=""
		for i in self.list_node:
			a="%s<!ELEMENT %s(" % (a,i.name())
			#get liste of node type i
			listenode=self.getChild(self.node_racine, i.name(), [], 0)
			for j in i.child():
				iteration=[]
				for x in listenode:
					iters=0
					for y in x.childNodes:
						if y.nodeName == j:
							iters=iters+1
					if iters > 1:
						iters=2 
					iteration.append(iters)
				sym=""			
				if 0 in iteration and 2 in iteration:
					sym="*"
				if 0 in iteration and 1 in iteration and 2 not in iteration:
					sym="?"
				if 0 not in iteration and 2 in iteration:
					sym="+"
 
				a="%s%s%s, " % (a,j,sym)
			if i.text() != None:
				a="%s%s, " % (a,"#PCDATA")			
			if a[-1]=="(":
				a= "%s>\n" % a[:-1]
			else:
				a= "%s)>\n" % a[:-2]
 
			if len(i.attr())>0:
				a= "%s<!ATTLIST %s\n" % (a,i.name())
				for j in i.attr():
					iteration=[]
					for x in listenode:
						iters=0
						if j.name() in x.attributes.keys():
							iters=1
						iteration.append(iters)
					sym=""				
					if 0 in iteration and 1 in iteration:
						sym="#IMPLIED"
					if 0 not in iteration :
						sym="#REQUIRED"					
					a= "%s\t%s CDATA %s\n" % (a,j.name(), sym)
				a="%s>\n" % a[:-1]
		return a
 
	def getSchema(self):
		xmldoc = Document()
		xmltag = xmldoc.createElement("xs:schema")
		xmltag.setAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema")
		xmldoc.appendChild(xmltag)
		for i in self.list_node:
			listenode=self.getChild(self.node_racine, i.name(), [], 0)
			xmlchild = xmldoc.createElement("xs:element")
			xmlchild.setAttribute("name", i.name())
			xmltag.appendChild(xmlchild)
			xmlType= xmldoc.createElement("xs:complexType")
			xmlType.setAttribute("mixed", "true")
			xmlchild.appendChild(xmlType)
			for j in i.child():
				xmlElt= xmldoc.createElement("xs:element")
				xmlElt.setAttribute("ref", j)				
				xmlType.appendChild(xmlElt)
 
			if len(i.attr())>0:
				for j in i.attr():
					iteration=[]
					for x in listenode:
						iters=0
						if j.name() in x.attributes.keys():
							iters=1
						iteration.append(iters)
					sym=""				
					if 0 in iteration and 1 in iteration:
						sym="optional"
					if 0 not in iteration :
						sym="required"
					xmlAttr= xmldoc.createElement("xs:attribute")
					xmlAttr.setAttribute("name", j.name())	
					xmlAttr.setAttribute("type", "xs:NMTOKEN")	
					xmlAttr.setAttribute("use", sym)			
					xmlType.appendChild(xmlAttr)	
		return xmldoc.toxml()
 
def usage():
	print "Usage:\n------\npython GenerateDTD.py -i in.xml\n"
	version()
 
def version():
	print "Version:\n--------\nGenerateDTD version %s by Frederic Aoustin" % pg_version
 
if __name__ == "__main__":
	try:
        	filein= ''
        	opts, args = getopt.getopt(sys.argv[1:], "hvi:", ["help"])
    		for opt, arg in opts:       
            		if opt in ("-h", "--help"):      
            			usage()                     
            			sys.exit()        
            		if opt in ("-v"):      
            			version()                     
            			sys.exit()                  
            		elif opt == '-i':              
            			filein= arg
        	if (filein != '' ):
             		xmldtd = XmlDTD(filein)
	     		xmldtd.parseDTD()
             		print xmldtd.getDTD()
        	else:
	     		usage()
 
    	except getopt.GetoptError:
        	print "Error"
        	usage()
 
    	except Exception,e:
        	print e | 
Partager