xmlclass/xsdschema.py
changeset 565 94c11207aa6f
child 592 89ff2738ef20
equal deleted inserted replaced
564:5024d42e1050 565:94c11207aa6f
       
     1 #!/usr/bin/env python
       
     2 # -*- coding: utf-8 -*-
       
     3 
       
     4 #This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor
       
     5 #based on the plcopen standard. 
       
     6 #
       
     7 #Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD
       
     8 #
       
     9 #See COPYING file for copyrights details.
       
    10 #
       
    11 #This library is free software; you can redistribute it and/or
       
    12 #modify it under the terms of the GNU General Public
       
    13 #License as published by the Free Software Foundation; either
       
    14 #version 2.1 of the License, or (at your option) any later version.
       
    15 #
       
    16 #This library is distributed in the hope that it will be useful,
       
    17 #but WITHOUT ANY WARRANTY; without even the implied warranty of
       
    18 #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
       
    19 #General Public License for more details.
       
    20 #
       
    21 #You should have received a copy of the GNU General Public
       
    22 #License along with this library; if not, write to the Free Software
       
    23 #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
       
    24 
       
    25 import re
       
    26 import datetime
       
    27 from xml.dom import minidom
       
    28 from types import *
       
    29 
       
    30 from xmlclass import *
       
    31 
       
    32 def GenerateDictFacets(facets):
       
    33     return dict([(name, (None, False)) for name in facets])
       
    34 
       
    35 def GenerateSimpleTypeXMLText(function):
       
    36     def generateXMLTextMethod(value, name=None, indent=0):
       
    37         text = ""
       
    38         if name is not None:
       
    39             ind1, ind2 = getIndent(indent, name)
       
    40             text += ind1 + "<%s>" % name
       
    41         text += function(value)
       
    42         if name is not None:
       
    43             text += "</%s>\n" % name
       
    44         return text
       
    45     return generateXMLTextMethod
       
    46 
       
    47 def GenerateFloatXMLText(extra_values=[]):
       
    48     def generateXMLTextMethod(value, name=None, indent=0):
       
    49         text = ""
       
    50         if name is not None:
       
    51             ind1, ind2 = getIndent(indent, name)
       
    52             text += ind1 + "<%s>" % name
       
    53         if value in extra_values or value % 1 != 0 or isinstance(value, IntType):
       
    54             text += str(value)
       
    55         else:
       
    56             text += "%.0f" % value
       
    57         if name is not None:
       
    58             text += "</%s>\n" % name
       
    59         return text
       
    60     return generateXMLTextMethod
       
    61         
       
    62 DEFAULT_FACETS = GenerateDictFacets(["pattern", "whiteSpace", "enumeration"])
       
    63 NUMBER_FACETS = GenerateDictFacets(DEFAULT_FACETS.keys() + ["maxInclusive", "maxExclusive", "minInclusive", "minExclusive"])
       
    64 DECIMAL_FACETS = GenerateDictFacets(NUMBER_FACETS.keys() + ["totalDigits", "fractionDigits"])
       
    65 STRING_FACETS = GenerateDictFacets(DEFAULT_FACETS.keys() + ["length", "minLength", "maxLength"])
       
    66 
       
    67 ALL_FACETS = ["pattern", "whiteSpace", "enumeration", "maxInclusive", 
       
    68     "maxExclusive", "minInclusive", "minExclusive", "totalDigits", 
       
    69     "fractionDigits", "length", "minLength", "maxLength"]
       
    70 
       
    71 
       
    72 #-------------------------------------------------------------------------------
       
    73 #                           Structure reducing functions
       
    74 #-------------------------------------------------------------------------------
       
    75 
       
    76 
       
    77 # Documentation elements
       
    78 
       
    79 def ReduceAppInfo(factory, attributes, elements):
       
    80     return {"type": "appinfo", "source": attributes.get("source", None), 
       
    81             "content": "\n".join(elements)}
       
    82 
       
    83 
       
    84 def ReduceDocumentation(factory, attributes, elements):
       
    85     return {"type": "documentation", "source": attributes.get("source", None), 
       
    86             "language": attributes.get("lang", "any"), "content": "\n".join(elements)}
       
    87 
       
    88 
       
    89 def ReduceAnnotation(factory, attributes, elements):
       
    90     annotations, children = factory.ReduceElements(elements)
       
    91     annotation = {"type": "annotation", "appinfo": [], "documentation": {}}
       
    92     for child in children:
       
    93         if child["type"] == "appinfo":
       
    94             annotation["appinfo"].append((child["source"], child["content"]))
       
    95         elif child["type"] == "documentation":
       
    96             if child["source"] is not None:
       
    97                 text = "(source: %(source)s):\n%(content)s\n\n"%child
       
    98             else:
       
    99                 text = child["content"] + "\n\n"
       
   100             if not annotation["documentation"].has_key(child["language"]):
       
   101                 annotation["documentation"] = text
       
   102             else:
       
   103                 annotation["documentation"] += text
       
   104     return annotation
       
   105 
       
   106 # Simple type elements
       
   107 
       
   108 def GenerateFacetReducing(facetname, canbefixed):
       
   109     def ReduceFacet(factory, attributes, elements):
       
   110         annotations, children = factory.ReduceElements(elements)
       
   111         if attributes.has_key("value"):
       
   112             facet = {"type": facetname, "value": attributes["value"], "doc": annotations}
       
   113             if canbefixed:
       
   114                 facet["fixed"] = attributes.get("fixed", False)
       
   115             return facet
       
   116         raise ValueError("A value must be defined for the \"%s\" facet!" % facetname)
       
   117     return ReduceFacet
       
   118 
       
   119 
       
   120 def ReduceList(factory, attributes, elements):
       
   121     annotations, children = factory.ReduceElements(elements)
       
   122     list = {"type": "list", "itemType": attributes.get("itemType", None), "doc": annotations}
       
   123     
       
   124     if len(children) > 0 and children[0]["type"] == SIMPLETYPE:
       
   125         if list["itemType"] is None:
       
   126             list["itemType"] = children[0]
       
   127         else:
       
   128             raise ValueError("Only one base type can be defined for restriction!")
       
   129     if list["itemType"] is None:
       
   130         raise ValueError("No base type has been defined for list!")
       
   131     return list
       
   132 
       
   133 
       
   134 def ReduceUnion(factory, attributes, elements):
       
   135     annotations, children = factory.ReduceElements(elements)
       
   136     union = {"type": "union", "memberTypes": attributes.get("memberTypes", []), "doc": annotations}
       
   137     
       
   138     for child in children:
       
   139         if child["type"] == SIMPLETYPE:
       
   140             union["memberTypes"].appendchild
       
   141     if len(union["memberTypes"]) == 0:
       
   142         raise ValueError("No base type has been defined for union!")
       
   143     return union
       
   144 
       
   145 
       
   146 def ReduceSimpleType(factory, attributes, elements):
       
   147     # Reduce all the simple type children
       
   148     annotations, children = factory.ReduceElements(elements)
       
   149     
       
   150     typeinfos = children[0]
       
   151     
       
   152     # Initialize type informations
       
   153     facets = {}
       
   154     simpleType = {"type": SIMPLETYPE, "final": attributes.get("final", []), "doc": annotations}
       
   155     if attributes.has_key("name"):
       
   156         simpleType["name"] = attributes["name"]
       
   157     
       
   158     if typeinfos["type"] == "restriction":
       
   159         # Search for base type definition
       
   160         if isinstance(typeinfos["base"], (StringType, UnicodeType)):
       
   161             basetypeinfos = factory.FindSchemaElement(typeinfos["base"], SIMPLETYPE)
       
   162             if basetypeinfos is None:
       
   163                 raise "\"%s\" isn't defined!" % typeinfos["base"] 
       
   164         else:
       
   165             basetypeinfos = typeinfos["base"]
       
   166         
       
   167         # Check that base type is a simple type
       
   168         if basetypeinfos["type"] != SIMPLETYPE:
       
   169             raise ValueError("Base type given isn't a simpleType!")
       
   170         
       
   171         simpleType["basename"] = basetypeinfos["basename"]
       
   172         
       
   173         # Check that derivation is allowed
       
   174         if basetypeinfos.has_key("final"):
       
   175             if basetypeinfos["final"].has_key("#all"):
       
   176                 raise ValueError("Base type can't be derivated!")
       
   177             if basetypeinfos["final"].has_key("restriction"):
       
   178                 raise ValueError("Base type can't be derivated by restriction!")
       
   179         
       
   180         # Extract simple type facets
       
   181         for facet in typeinfos["facets"]:
       
   182             facettype = facet["type"]
       
   183             if not basetypeinfos["facets"].has_key(facettype):
       
   184                 raise ValueError("\"%s\" facet can't be defined for \"%s\" type!" % (facettype, type))
       
   185             elif basetypeinfos["facets"][facettype][1]:
       
   186                 raise ValueError("\"%s\" facet is fixed on base type!" % facettype)
       
   187             value = facet["value"]
       
   188             basevalue = basetypeinfos["facets"][facettype][0]
       
   189             if facettype == "enumeration":
       
   190                 value = basetypeinfos["extract"](value, False)
       
   191                 if len(facets) == 0:
       
   192                     facets["enumeration"] = ([value], False)
       
   193                     continue
       
   194                 elif facets.keys() == ["enumeration"]:
       
   195                     facets["enumeration"][0].append(value)
       
   196                     continue
       
   197                 else:
       
   198                     raise ValueError("\"enumeration\" facet can't be defined with another facet type!")
       
   199             elif facets.has_key("enumeration"):
       
   200                 raise ValueError("\"enumeration\" facet can't be defined with another facet type!")
       
   201             elif facets.has_key(facettype):
       
   202                 raise ValueError("\"%s\" facet can't be defined two times!" % facettype)
       
   203             elif facettype == "length":
       
   204                 if facets.has_key("minLength"):
       
   205                     raise ValueError("\"length\" and \"minLength\" facets can't be defined at the same time!")
       
   206                 if facets.has_key("maxLength"):
       
   207                     raise ValueError("\"length\" and \"maxLength\" facets can't be defined at the same time!")
       
   208                 try:
       
   209                     value = int(value)
       
   210                 except:
       
   211                     raise ValueError("\"length\" must be an integer!")
       
   212                 if value < 0:
       
   213                     raise ValueError("\"length\" can't be negative!")
       
   214                 elif basevalue is not None and basevalue != value:
       
   215                     raise ValueError("\"length\" can't be different from \"length\" defined in base type!")
       
   216             elif facettype == "minLength":
       
   217                 if facets.has_key("length"):
       
   218                     raise ValueError("\"length\" and \"minLength\" facets can't be defined at the same time!")
       
   219                 try:
       
   220                     value = int(value)
       
   221                 except:
       
   222                     raise ValueError("\"minLength\" must be an integer!")
       
   223                 if value < 0:
       
   224                     raise ValueError("\"minLength\" can't be negative!")
       
   225                 elif facets.has_key("maxLength") and value > facets["maxLength"]:
       
   226                     raise ValueError("\"minLength\" must be lesser than or equal to \"maxLength\"!")
       
   227                 elif basevalue is not None and basevalue < value:
       
   228                     raise ValueError("\"minLength\" can't be lesser than \"minLength\" defined in base type!")
       
   229             elif facettype == "maxLength":
       
   230                 if facets.has_key("length"):
       
   231                     raise ValueError("\"length\" and \"maxLength\" facets can't be defined at the same time!")
       
   232                 try:
       
   233                     value = int(value)
       
   234                 except:
       
   235                     raise ValueError("\"maxLength\" must be an integer!")
       
   236                 if value < 0:
       
   237                     raise ValueError("\"maxLength\" can't be negative!")
       
   238                 elif facets.has_key("minLength") and value < facets["minLength"]:
       
   239                     raise ValueError("\"minLength\" must be lesser than or equal to \"maxLength\"!")
       
   240                 elif basevalue is not None and basevalue > value:
       
   241                     raise ValueError("\"maxLength\" can't be greater than \"maxLength\" defined in base type!")
       
   242             elif facettype == "minInclusive":
       
   243                 if facets.has_key("minExclusive"):
       
   244                     raise ValueError("\"minExclusive\" and \"minInclusive\" facets can't be defined at the same time!")
       
   245                 value = basetypeinfos["extract"](facet["value"], False)
       
   246                 if facets.has_key("maxInclusive") and value > facets["maxInclusive"][0]:
       
   247                     raise ValueError("\"minInclusive\" must be lesser than or equal to \"maxInclusive\"!")
       
   248                 elif facets.has_key("maxExclusive") and value >= facets["maxExclusive"][0]:
       
   249                     raise ValueError("\"minInclusive\" must be lesser than \"maxExclusive\"!")
       
   250             elif facettype == "minExclusive":
       
   251                 if facets.has_key("minInclusive"):
       
   252                     raise ValueError("\"minExclusive\" and \"minInclusive\" facets can't be defined at the same time!")
       
   253                 value = basetypeinfos["extract"](facet["value"], False)
       
   254                 if facets.has_key("maxInclusive") and value >= facets["maxInclusive"][0]:
       
   255                     raise ValueError("\"minExclusive\" must be lesser than \"maxInclusive\"!")
       
   256                 elif facets.has_key("maxExclusive") and value >= facets["maxExclusive"][0]:
       
   257                     raise ValueError("\"minExclusive\" must be lesser than \"maxExclusive\"!")
       
   258             elif facettype == "maxInclusive":
       
   259                 if facets.has_key("maxExclusive"):
       
   260                     raise ValueError("\"maxExclusive\" and \"maxInclusive\" facets can't be defined at the same time!")
       
   261                 value = basetypeinfos["extract"](facet["value"], False)
       
   262                 if facets.has_key("minInclusive") and value < facets["minInclusive"][0]:
       
   263                     raise ValueError("\"minInclusive\" must be lesser than or equal to \"maxInclusive\"!")
       
   264                 elif facets.has_key("minExclusive") and value <= facets["minExclusive"][0]:
       
   265                     raise ValueError("\"minExclusive\" must be lesser than \"maxInclusive\"!")
       
   266             elif facettype == "maxExclusive":
       
   267                 if facets.has_key("maxInclusive"):
       
   268                     raise ValueError("\"maxExclusive\" and \"maxInclusive\" facets can't be defined at the same time!")
       
   269                 value = basetypeinfos["extract"](facet["value"], False)
       
   270                 if facets.has_key("minInclusive") and value <= facets["minInclusive"][0]:
       
   271                     raise ValueError("\"minInclusive\" must be lesser than \"maxExclusive\"!")
       
   272                 elif facets.has_key("minExclusive") and value <= facets["minExclusive"][0]:
       
   273                     raise ValueError("\"minExclusive\" must be lesser than \"maxExclusive\"!")
       
   274             elif facettype == "whiteSpace":
       
   275                 if basevalue == "collapse" and value in ["preserve", "replace"] or basevalue == "replace" and value == "preserve":
       
   276                    raise ValueError("\"whiteSpace\" is incompatible with \"whiteSpace\" defined in base type!")
       
   277             elif facettype == "totalDigits":
       
   278                 if facets.has_key("fractionDigits") and value <= facets["fractionDigits"][0]:
       
   279                     raise ValueError("\"fractionDigits\" must be lesser than or equal to \"totalDigits\"!")
       
   280                 elif basevalue is not None and value > basevalue:
       
   281                     raise ValueError("\"totalDigits\" can't be greater than \"totalDigits\" defined in base type!")
       
   282             elif facettype == "fractionDigits":
       
   283                 if facets.has_key("totalDigits") and value <= facets["totalDigits"][0]:
       
   284                     raise ValueError("\"fractionDigits\" must be lesser than or equal to \"totalDigits\"!")
       
   285                 elif basevalue is not None and value > basevalue:
       
   286                     raise ValueError("\"totalDigits\" can't be greater than \"totalDigits\" defined in base type!")
       
   287             facets[facettype] = (value, facet.get("fixed", False))
       
   288         
       
   289         # Report not redefined facet from base type to new created type 
       
   290         for facettype, facetvalue in basetypeinfos["facets"].items():
       
   291             if not facets.has_key(facettype):
       
   292                 facets[facettype] = facetvalue
       
   293         
       
   294         # Generate extract value for new created type
       
   295         def ExtractSimpleTypeValue(attr, extract=True):
       
   296             value = basetypeinfos["extract"](attr, extract)
       
   297             for facetname, (facetvalue, facetfixed) in facets.items():
       
   298                 if facetvalue is not None:
       
   299                     if facetname == "enumeration" and value not in facetvalue:
       
   300                         raise ValueError("\"%s\" not in enumerated values" % value)
       
   301                     elif facetname == "length" and len(value) != facetvalue:
       
   302                         raise ValueError("value must have a length of %d" % facetvalue)
       
   303                     elif facetname == "minLength" and len(value) < facetvalue:
       
   304                         raise ValueError("value must have a length of %d at least" % facetvalue)
       
   305                     elif facetname == "maxLength" and len(value) > facetvalue:
       
   306                         raise ValueError("value must have a length of %d at most" % facetvalue)
       
   307                     elif facetname == "minInclusive" and value < facetvalue:
       
   308                         raise ValueError("value must be greater than or equal to %s" % str(facetvalue))
       
   309                     elif facetname == "minExclusive" and value <= facetvalue:
       
   310                         raise ValueError("value must be greater than %s" % str(facetvalue))
       
   311                     elif facetname == "maxInclusive" and value > facetvalue:
       
   312                         raise ValueError("value must be lesser than or equal to %s" % str(facetvalue))
       
   313                     elif facetname == "maxExclusive"  and value >= facetvalue:
       
   314                         raise ValueError("value must be lesser than %s" % str(facetvalue))
       
   315                     elif facetname == "pattern":
       
   316                         model = re.compile("(?:%s)?$" % facetvalue)
       
   317                         result = model.match(value)
       
   318                         if result is None:
       
   319                             raise ValueError("value doesn't follow the pattern %s" % facetvalue)
       
   320                     elif facetname == "whiteSpace":
       
   321                         if facetvalue == "replace":
       
   322                             value = GetNormalizedString(value, False)
       
   323                         elif facetvalue == "collapse":
       
   324                             value = GetToken(value, False)
       
   325             return value
       
   326         
       
   327         def CheckSimpleTypeValue(value):
       
   328             for facetname, (facetvalue, facetfixed) in facets.items():
       
   329                 if facetvalue is not None:
       
   330                     if facetname == "enumeration" and value not in facetvalue:
       
   331                         return False
       
   332                     elif facetname == "length" and len(value) != facetvalue:
       
   333                         return False
       
   334                     elif facetname == "minLength" and len(value) < facetvalue:
       
   335                         return False
       
   336                     elif facetname == "maxLength" and len(value) > facetvalue:
       
   337                         return False
       
   338                     elif facetname == "minInclusive" and value < facetvalue:
       
   339                         return False
       
   340                     elif facetname == "minExclusive" and value <= facetvalue:
       
   341                         return False
       
   342                     elif facetname == "maxInclusive" and value > facetvalue:
       
   343                         return False
       
   344                     elif facetname == "maxExclusive"  and value >= facetvalue:
       
   345                         return False
       
   346                     elif facetname == "pattern":
       
   347                         model = re.compile("(?:%s)?$" % facetvalue)
       
   348                         result = model.match(value)
       
   349                         if result is None:
       
   350                             raise ValueError("value doesn't follow the pattern %s" % facetvalue)
       
   351             return True
       
   352         
       
   353         def SimpleTypeInitialValue():
       
   354             for facetname, (facetvalue, facetfixed) in facets.items():
       
   355                 if facetvalue is not None:
       
   356                     if facetname == "enumeration":
       
   357                         return facetvalue[0]
       
   358                     elif facetname == "length":
       
   359                         return " "*facetvalue
       
   360                     elif facetname == "minLength":
       
   361                         return " "*minLength
       
   362                     elif facetname == "minInclusive" and facetvalue > 0:
       
   363                         return facetvalue
       
   364                     elif facetname == "minExclusive" and facetvalue >= 0:
       
   365                         return facetvalue + 1
       
   366                     elif facetname == "maxInclusive" and facetvalue < 0:
       
   367                         return facetvalue
       
   368                     elif facetname == "maxExclusive"  and facetvalue <= 0:
       
   369                         return facetvalue - 1
       
   370             return basetypeinfos["initial"]()
       
   371         
       
   372         GenerateSimpleType = basetypeinfos["generate"]
       
   373         
       
   374     elif typeinfos["type"] == "list":
       
   375         # Search for item type definition
       
   376         if isinstance(typeinfos["itemType"], (StringType, UnicodeType)):
       
   377             itemtypeinfos = factory.FindSchemaElement(typeinfos["itemType"], SIMPLETYPE)
       
   378             if itemtypeinfos is None:
       
   379                 raise "\"%s\" isn't defined!" % typeinfos["itemType"]
       
   380         else:
       
   381             itemtypeinfos = typeinfos["itemType"]
       
   382         
       
   383         # Check that item type is a simple type
       
   384         if itemtypeinfos["type"] != SIMPLETYPE:
       
   385             raise ValueError, "Item type given isn't a simpleType!"
       
   386         
       
   387         simpleType["basename"] = "list"
       
   388         
       
   389         # Check that derivation is allowed
       
   390         if itemtypeinfos.has_key("final"):
       
   391             if itemtypeinfos["final"].has_key("#all"):
       
   392                 raise ValueError("Item type can't be derivated!")
       
   393             if itemtypeinfos["final"].has_key("list"):
       
   394                 raise ValueError("Item type can't be derivated by list!")
       
   395         
       
   396         # Generate extract value for new created type
       
   397         def ExtractSimpleTypeValue(attr, extract = True):
       
   398             values = []
       
   399             for value in GetToken(attr, extract).split(" "):
       
   400                 values.append(itemtypeinfos["extract"](value, False))
       
   401             return values
       
   402         
       
   403         def CheckSimpleTypeValue(value):
       
   404             for item in value:
       
   405                 result = itemtypeinfos["check"](item)
       
   406                 if not result:
       
   407                     return result
       
   408             return True
       
   409         
       
   410         SimpleTypeInitialValue = lambda: []
       
   411         
       
   412         GenerateSimpleType = GenerateSimpleTypeXMLText(lambda x: " ".join(map(itemtypeinfos["generate"], x)))
       
   413         
       
   414         facets = GenerateDictFacets(["length", "maxLength", "minLength", "enumeration", "pattern"])
       
   415         facets["whiteSpace"] = ("collapse", False)
       
   416     
       
   417     elif typeinfos["type"] == "union":
       
   418         # Search for member types definition
       
   419         membertypesinfos = []
       
   420         for membertype in typeinfos["memberTypes"]:
       
   421             if isinstance(membertype, (StringType, UnicodeType)):
       
   422                 infos = factory.FindSchemaElement(membertype, SIMPLETYPE)
       
   423                 if infos is None:
       
   424                     raise ValueError("\"%s\" isn't defined!" % membertype)
       
   425             else:
       
   426                 infos = membertype
       
   427             
       
   428             # Check that member type is a simple type
       
   429             if infos["type"] != SIMPLETYPE:
       
   430                 raise ValueError("Member type given isn't a simpleType!")
       
   431             
       
   432             # Check that derivation is allowed
       
   433             if infos.has_key("final"):
       
   434                 if infos["final"].has_key("#all"):
       
   435                     raise ValueError("Item type can't be derivated!")
       
   436                 if infos["final"].has_key("union"):
       
   437                     raise ValueError("Member type can't be derivated by union!")
       
   438             
       
   439             membertypesinfos.append(infos)
       
   440         
       
   441         simpleType["basename"] = "union"
       
   442         
       
   443         # Generate extract value for new created type
       
   444         def ExtractSimpleTypeValue(attr, extract = True):
       
   445             if extract:
       
   446                 value = GetAttributeValue(attr)
       
   447             else:
       
   448                 value = attr
       
   449             for infos in membertypesinfos:
       
   450                 try:
       
   451                     return infos["extract"](attr, False)
       
   452                 except:
       
   453                     pass
       
   454             raise ValueError("\"%s\" isn't valid for type defined for union!")
       
   455         
       
   456         def CheckSimpleTypeValue(value):
       
   457             for infos in membertypesinfos:
       
   458                 result = infos["check"](value)
       
   459                 if result:
       
   460                     return result
       
   461             return False
       
   462         
       
   463         SimpleTypeInitialValue = membertypesinfos[0]["initial"]
       
   464         
       
   465         def GenerateSimpleTypeFunction(value):
       
   466             if isinstance(value, BooleanType):
       
   467                 return {True: "true", False: "false"}[value]
       
   468             else:
       
   469                 return str(value)
       
   470         GenerateSimpleType = GenerateSimpleTypeXMLText(GenerateSimpleTypeFunction)
       
   471         
       
   472         facets = GenerateDictFacets(["pattern", "enumeration"])
       
   473     
       
   474     simpleType["facets"] = facets
       
   475     simpleType["extract"] = ExtractSimpleTypeValue
       
   476     simpleType["initial"] = SimpleTypeInitialValue
       
   477     simpleType["check"] = CheckSimpleTypeValue
       
   478     simpleType["generate"] = GenerateSimpleType
       
   479     return simpleType
       
   480 
       
   481 
       
   482 # Complex type
       
   483 
       
   484 def ExtractAttributes(factory, elements, base = None):
       
   485     if base is not None:
       
   486         basetypeinfos = factory.FindSchemaElement(base, COMPLEXTYPE)
       
   487         if isinstance(basetypeinfos, (UnicodeType, StringType)):
       
   488             attrnames = {}
       
   489         else:
       
   490             attrnames = dict(map(lambda x:(x["name"], True), basetypeinfos["attributes"]))
       
   491     else:
       
   492         attrnames = {}
       
   493     attrs = []
       
   494     for element in elements:
       
   495         if element["type"] == ATTRIBUTE:
       
   496             if attrnames.get(element["name"], False):
       
   497                 raise ValueError("\"%s\" attribute has been defined two times!" % element["name"])
       
   498             else:
       
   499                 attrnames[element["name"]] = True
       
   500                 attrs.append(element)
       
   501         elif element["type"] == "attributeGroup":
       
   502             attrgroup = factory.FindSchemaElement(element["ref"], ATTRIBUTESGROUP)
       
   503             for attr in attrgroup["attributes"]:
       
   504                 if attrnames.get(attr["name"], False):
       
   505                     raise ValueError("\"%s\" attribute has been defined two times!" % attr["name"])
       
   506                 else:
       
   507                     attrnames[attr["name"]] = True
       
   508                     attrs.append(attr)
       
   509         elif element["type"] == "anyAttribute":
       
   510             raise ValueError("\"anyAttribute\" element isn't supported yet!")
       
   511     return attrs
       
   512 
       
   513 
       
   514 def ReduceRestriction(factory, attributes, elements):
       
   515     annotations, children = factory.ReduceElements(elements)
       
   516     restriction = {"type": "restriction", "base": attributes.get("base", None), "facets": [], "doc": annotations}
       
   517     if len(children) > 0 and children[0]["type"] == SIMPLETYPE:
       
   518         if restriction["base"] is None:
       
   519             restriction["base"] = children.pop(0)
       
   520         else:
       
   521             raise ValueError("Only one base type can be defined for restriction!")
       
   522     if restriction["base"] is None:
       
   523         raise ValueError("No base type has been defined for restriction!")
       
   524     
       
   525     while len(children) > 0 and children[0]["type"] in ALL_FACETS:
       
   526         restriction["facets"].append(children.pop(0))
       
   527     restriction["attributes"] = ExtractAttributes(factory, children)
       
   528     return restriction
       
   529 
       
   530 
       
   531 def ReduceExtension(factory, attributes, elements):
       
   532     annotations, children = factory.ReduceElements(elements)
       
   533     extension = {"type": "extension", "attributes": [], "elements": [], "base": attributes.get("base", None), "doc": annotations}
       
   534     if len(children) > 0:
       
   535         if children[0]["type"] in ["group", "all", CHOICE, "sequence"]:
       
   536             group = children.pop(0)
       
   537             if group["type"] in ["all", "sequence"]:
       
   538                 extension["elements"] = group["elements"]
       
   539                 extension["order"] = group["order"]
       
   540             elif group["type"] == CHOICE:
       
   541                 content = group.copy()
       
   542                 content["name"] = "content"
       
   543                 extension["elements"].append(content)
       
   544             elif group["type"] == "group":
       
   545                 elmtgroup = factory.FindSchemaElement(child["ref"], ELEMENTSGROUP)
       
   546                 if elmtgroup.has_key("elements"):
       
   547                     extension["elements"] = elmtgroup["elements"]
       
   548                     extension["order"] = elmtgroup["order"]
       
   549                 else:
       
   550                     content = elmtgroup.copy()
       
   551                     content["name"] = "content"
       
   552                     extension["elements"].append(content)
       
   553         extension["attributes"] = ExtractAttributes(factory, children, extension["base"])
       
   554     return extension
       
   555 
       
   556 
       
   557 def ReduceSimpleContent(factory, attributes, elements):
       
   558     annotations, children = factory.ReduceElements(elements)
       
   559     simpleContent = children[0].copy()
       
   560     simpleContent["type"] = "simpleContent"
       
   561     return simpleContent
       
   562 
       
   563 
       
   564 def ReduceComplexContent(factory, attributes, elements):
       
   565     annotations, children = factory.ReduceElements(elements)
       
   566     complexContent = children[0].copy()
       
   567     complexContent["type"] = "complexContent"
       
   568     return complexContent
       
   569 
       
   570 
       
   571 def ReduceComplexType(factory, attributes, elements):
       
   572     annotations, children = factory.ReduceElements(elements)
       
   573         
       
   574     if len(children) > 0:
       
   575         if children[0]["type"] in ["simpleContent", "complexContent"]:
       
   576             complexType = children[0].copy()
       
   577             complexType.update(attributes)
       
   578             complexType["type"] = COMPLEXTYPE
       
   579             return complexType
       
   580         elif children[0]["type"] in ["group", "all", CHOICE, "sequence"]:
       
   581             complexType = {"type": COMPLEXTYPE, "elements": [], "order": True, "doc": annotations}
       
   582             complexType.update(attributes)
       
   583             group = children.pop(0)
       
   584             if group["type"] in ["all", "sequence"]:
       
   585                 if group["minOccurs"] == 0 or group["maxOccurs"] != 1:
       
   586                     if len(group["elements"]) > 1:
       
   587                         raise ValueError("Not supported yet!")
       
   588                     if group["minOccurs"] == 0:
       
   589                         group["elements"][0]["minOccurs"] = group["minOccurs"]
       
   590                     if group["maxOccurs"] != 1:
       
   591                         group["elements"][0]["maxOccurs"] = group["maxOccurs"]
       
   592                 complexType["elements"] = group["elements"]
       
   593                 complexType["order"] = group["order"]
       
   594             elif group["type"] == CHOICE:
       
   595                 content = group.copy()
       
   596                 content["name"] = "content"
       
   597                 complexType["elements"].append(content)
       
   598             elif group["type"] == "group":
       
   599                 elmtgroup = factory.FindSchemaElement(child["ref"], ELEMENTSGROUP)
       
   600                 if elmtgroup.has_key("elements"):
       
   601                     complexType["elements"] = elmtgroup["elements"]
       
   602                     complexType["order"] = elmtgroup["order"]
       
   603                 else:
       
   604                     content = elmtgroup.copy()
       
   605                     content["name"] = "content"
       
   606                     complexType["elements"].append(content)
       
   607         else:
       
   608             complexType = {"elements": [], "order": True, "doc": annotations}
       
   609             complexType.update(attributes)
       
   610             complexType["type"] = COMPLEXTYPE
       
   611         complexType["attributes"] = ExtractAttributes(factory, children)
       
   612         return complexType
       
   613     else:
       
   614         raise ValueError("\"ComplexType\" can't be empty!")
       
   615 
       
   616 
       
   617 # Attribute elements
       
   618 
       
   619 def ReduceAnyAttribute(factory, attributes, elements):
       
   620     return {"type" : "anyAttribute"}
       
   621 
       
   622 
       
   623 def ReduceAttribute(factory, attributes, elements):
       
   624     annotations, children = factory.ReduceElements(elements)
       
   625     
       
   626     if attributes.has_key("default"):
       
   627         if attributes.has_key("fixed"):
       
   628             raise ValueError("\"default\" and \"fixed\" can't be defined at the same time!")
       
   629         elif attributes.get("use", "optional") != "optional":
       
   630             raise ValueError("if \"default\" present, \"use\" can only have the value \"optional\"!")
       
   631     
       
   632     attribute = {"type": ATTRIBUTE, "attr_type": attributes.get("type", None), "doc": annotations}
       
   633     if len(children) > 0:
       
   634         if attribute["attr_type"] is None:
       
   635             attribute["attr_type"] = children[0]
       
   636         else:
       
   637             raise ValueError("Only one type can be defined for attribute!")
       
   638     
       
   639     if attributes.has_key("ref"):
       
   640         if attributes.has_key("name"):
       
   641             raise ValueError("\"ref\" and \"name\" can't be defined at the same time!")
       
   642         elif attributes.has_key("form"):
       
   643             raise ValueError("\"ref\" and \"form\" can't be defined at the same time!")
       
   644         elif attribute["attr_type"] is not None:
       
   645             raise ValueError("if \"ref\" is present, no type can be defined!")
       
   646     elif attribute["attr_type"] is None:
       
   647         raise ValueError("No type has been defined for attribute \"%s\"!" % attributes["name"])
       
   648     
       
   649     if attributes.has_key("type"):
       
   650         tmp_attrs = attributes.copy()
       
   651         tmp_attrs.pop("type")
       
   652         attribute.update(tmp_attrs)
       
   653     else:
       
   654         attribute.update(attributes)
       
   655     return attribute
       
   656 
       
   657 
       
   658 def ReduceAttributeGroup(factory, attributes, elements):
       
   659     annotations, children = factory.ReduceElements(elements)
       
   660     if attributes.has_key("ref"):
       
   661         return {"type": "attributeGroup", "ref": attributes["ref"], "doc": annotations}
       
   662     else:
       
   663         return {"type": ATTRIBUTESGROUP, "attributes": ExtractAttributes(factory, children), "doc": annotations}
       
   664 
       
   665 
       
   666 # Elements groups
       
   667 
       
   668 def ReduceAny(factory, attributes, elements):
       
   669     annotations, children = factory.ReduceElements(elements)
       
   670     
       
   671     any = {"type": ANY, "doc": annotations}
       
   672     any.update(attributes)
       
   673     return any
       
   674 
       
   675 def ReduceElement(factory, attributes, elements):
       
   676     if attributes.has_key("default") and attributes.has_key("fixed"):
       
   677         raise ValueError("\"default\" and \"fixed\" can't be defined at the same time!")
       
   678     
       
   679     if attributes.has_key("ref"):
       
   680         annotations, children = factory.ReduceElements(elements)
       
   681         
       
   682         for attr in ["name", "default", "fixed", "form", "block", "type"]:
       
   683             if attributes.has_key(attr):
       
   684                 raise ValueError("\"ref\" and \"%s\" can't be defined at the same time!" % attr)
       
   685         if attributes.has_key("nillable"):
       
   686             raise ValueError("\"ref\" and \"nillable\" can't be defined at the same time!")
       
   687         if len(children) > 0:
       
   688             raise ValueError("No type and no constraints can be defined where \"ref\" is defined!")
       
   689     
       
   690         infos = factory.FindSchemaElement(attributes["ref"], ELEMENT)
       
   691         if infos is not None:
       
   692             element = infos.copy()
       
   693             element["minOccurs"] = attributes["minOccurs"]
       
   694             element["maxOccurs"] = attributes["maxOccurs"]
       
   695             return element
       
   696         else:
       
   697             raise ValueError("\"%s\" base type isn't defined or circular referenced!" % name)
       
   698     
       
   699     elif attributes.has_key("name"):
       
   700         annotations, children = factory.ReduceElements(elements)
       
   701         
       
   702         element = {"type": ELEMENT, "elmt_type": attributes.get("type", None), "doc": annotations}
       
   703         if len(children) > 0:
       
   704             if element["elmt_type"] is None:
       
   705                 element["elmt_type"] = children[0]
       
   706             else:
       
   707                 raise ValueError("Only one type can be defined for attribute!")
       
   708         elif element["elmt_type"] is None:
       
   709             element["elmt_type"] = "tag"
       
   710             element["type"] = TAG
       
   711         
       
   712         if attributes.has_key("type"):
       
   713             tmp_attrs = attributes.copy()
       
   714             tmp_attrs.pop("type")
       
   715             element.update(tmp_attrs)
       
   716         else:
       
   717             element.update(attributes)
       
   718         return element
       
   719     else:
       
   720         raise ValueError("\"Element\" must have at least a \"ref\" or a \"name\" defined!")
       
   721 
       
   722 def ReduceAll(factory, attributes, elements):
       
   723     annotations, children = factory.ReduceElements(elements)
       
   724     
       
   725     for child in children:
       
   726         if children["maxOccurs"] == "unbounded" or children["maxOccurs"] > 1:
       
   727             raise ValueError("\"all\" item can't have \"maxOccurs\" attribute greater than 1!")
       
   728     
       
   729     return {"type": "all", "elements": children, "minOccurs": attributes["minOccurs"],
       
   730             "maxOccurs": attributes["maxOccurs"], "order": False, "doc": annotations}
       
   731 
       
   732 
       
   733 def ReduceChoice(factory, attributes, elements):
       
   734     annotations, children = factory.ReduceElements(elements)
       
   735     
       
   736     choices = []
       
   737     for child in children:
       
   738         if child["type"] in [ELEMENT, ANY, TAG]:
       
   739             choices.append(child)
       
   740         elif child["type"] == "sequence":
       
   741             raise ValueError("\"sequence\" in \"choice\" is not supported. Create instead a new complex type!")
       
   742         elif child["type"] == CHOICE:
       
   743             choices.extend(child["choices"])
       
   744         elif child["type"] == "group":
       
   745             elmtgroup = factory.FindSchemaElement(child["ref"], ELEMENTSGROUP) 
       
   746             if not elmtgroup.has_key("choices"):
       
   747                 raise ValueError("Only group composed of \"choice\" can be referenced in \"choice\" element!")
       
   748             choices_tmp = []
       
   749             for choice in elmtgroup["choices"]:
       
   750                 if not isinstance(choice["elmt_type"], (UnicodeType, StringType)) and choice["elmt_type"]["type"] == COMPLEXTYPE:
       
   751                     elmt_type = "%s_%s" % (elmtgroup["name"], choice["name"])
       
   752                     if factory.TargetNamespace is not None:
       
   753                         elmt_type = "%s:%s" % (factory.TargetNamespace, elmt_type)
       
   754                     new_choice = choice.copy()
       
   755                     new_choice["elmt_type"] = elmt_type
       
   756                     choices_tmp.append(new_choice)
       
   757                 else:
       
   758                     choices_tmp.append(choice)
       
   759             choices.extend(choices_tmp)
       
   760     
       
   761     return {"type": CHOICE, "choices": choices, "minOccurs": attributes["minOccurs"],
       
   762             "maxOccurs": attributes["maxOccurs"], "doc": annotations}
       
   763 
       
   764 
       
   765 def ReduceSequence(factory, attributes, elements):
       
   766     annotations, children = factory.ReduceElements(elements)
       
   767     
       
   768     sequence = []
       
   769     for child in children:
       
   770         if child["type"] in [ELEMENT, ANY, TAG]:
       
   771             sequence.append(child)
       
   772         elif child["type"] == CHOICE:
       
   773             content = child.copy()
       
   774             content["name"] = "content"
       
   775             sequence.append(content)
       
   776         elif child["type"] == "sequence":
       
   777             sequence.extend(child["elements"])
       
   778         elif child["type"] == "group":
       
   779             elmtgroup = factory.FindSchemaElement(child["ref"], ELEMENTSGROUP)
       
   780             if not elmtgroup.has_key("elements") or not elmtgroup["order"]:
       
   781                 raise ValueError("Only group composed of \"sequence\" can be referenced in \"sequence\" element!")
       
   782             elements_tmp = []
       
   783             for element in elmtgroup["elements"]:
       
   784                 if not isinstance(element["elmt_type"], (UnicodeType, StringType)) and element["elmt_type"]["type"] == COMPLEXTYPE:
       
   785                     elmt_type = "%s_%s"%(elmtgroup["name"], element["name"])
       
   786                     if factory.TargetNamespace is not None:
       
   787                         elmt_type = "%s:%s" % (factory.TargetNamespace, elmt_type)
       
   788                     new_element = element.copy()
       
   789                     new_element["elmt_type"] = elmt_type
       
   790                     elements_tmp.append(new_element)
       
   791                 else:
       
   792                     elements_tmp.append(element)
       
   793             sequence.extend(elements_tmp)
       
   794             
       
   795     return {"type": "sequence", "elements": sequence, "minOccurs": attributes["minOccurs"],
       
   796             "maxOccurs": attributes["maxOccurs"], "order": True, "doc": annotations}
       
   797     
       
   798     
       
   799 def ReduceGroup(factory, attributes, elements):
       
   800     annotations, children = factory.ReduceElements(elements)
       
   801     
       
   802     if attributes.has_key("ref"):
       
   803         return {"type": "group", "ref": attributes["ref"], "doc": annotations}
       
   804     else:
       
   805         element = children[0]
       
   806         group = {"type": ELEMENTSGROUP, "doc": annotations}
       
   807         if element["type"] == CHOICE:
       
   808             group["choices"] = element["choices"]
       
   809         else:
       
   810             group.update({"elements": element["elements"], "order": group["order"]})
       
   811         group.update(attributes)
       
   812         return group
       
   813 
       
   814 # Constraint elements
       
   815 
       
   816 def ReduceUnique(factory, attributes, elements):
       
   817     annotations, children = factory.ReduceElements(elements)
       
   818     raise ValueError("\"unique\" element isn't supported yet!")
       
   819 
       
   820 def ReduceKey(factory, attributes, elements):
       
   821     annotations, children = factory.ReduceElements(elements)
       
   822     raise ValueError("\"key\" element isn't supported yet!")
       
   823     
       
   824 def ReduceKeyRef(factory, attributes, elements):
       
   825     annotations, children = factory.ReduceElements(elements)
       
   826     raise ValueError("\"keyref\" element isn't supported yet!")
       
   827     
       
   828 def ReduceSelector(factory, attributes, elements):
       
   829     annotations, children = factory.ReduceElements(elements)
       
   830     raise ValueError("\"selector\" element isn't supported yet!")
       
   831 
       
   832 def ReduceField(factory, attributes, elements):
       
   833     annotations, children = factory.ReduceElements(elements)
       
   834     raise ValueError("\"field\" element isn't supported yet!")
       
   835     
       
   836 
       
   837 # Inclusion elements
       
   838 
       
   839 def ReduceImport(factory, attributes, elements):
       
   840     annotations, children = factory.ReduceElements(elements)
       
   841     raise ValueError("\"import\" element isn't supported yet!")
       
   842 
       
   843 def ReduceInclude(factory, attributes, elements):
       
   844     annotations, children = factory.ReduceElements(elements)
       
   845     raise ValueError("\"include\" element isn't supported yet!")
       
   846     
       
   847 def ReduceRedefine(factory, attributes, elements):
       
   848     annotations, children = factory.ReduceElements(elements)
       
   849     raise ValueError("\"redefine\" element isn't supported yet!")
       
   850 
       
   851 
       
   852 # Schema element
       
   853 
       
   854 def ReduceSchema(factory, attributes, elements):
       
   855     factory.AttributeFormDefault = attributes["attributeFormDefault"]
       
   856     factory.ElementFormDefault = attributes["elementFormDefault"]
       
   857     factory.BlockDefault = attributes["blockDefault"]
       
   858     factory.FinalDefault = attributes["finalDefault"]
       
   859     
       
   860     if attributes.has_key("targetNamespace"):
       
   861         factory.TargetNamespace = factory.DefinedNamespaces.get(attributes["targetNamespace"], None)
       
   862     factory.Namespaces[factory.TargetNamespace] = {}
       
   863     
       
   864     annotations, children = factory.ReduceElements(elements, True)
       
   865     
       
   866     for child in children:
       
   867         if child.has_key("name"):
       
   868             infos = factory.GetQualifiedNameInfos(child["name"], factory.TargetNamespace, True)
       
   869             if infos is None:
       
   870                 factory.Namespaces[factory.TargetNamespace][child["name"]] = child
       
   871             elif not CompareSchema(infos, child):
       
   872                 raise ValueError("\"%s\" is defined twice in targetNamespace!" % child["name"])
       
   873 
       
   874 def CompareSchema(schema, reference):
       
   875     if isinstance(schema, ListType):
       
   876         if not isinstance(reference, ListType) or len(schema) != len(reference):
       
   877             return False
       
   878         for i, value in enumerate(schema):
       
   879             result = CompareSchema(value, reference[i])
       
   880             if not result:
       
   881                 return result
       
   882         return True
       
   883     elif isinstance(schema, DictType):
       
   884         if not isinstance(reference, DictType) or len(schema) != len(reference):
       
   885             return False
       
   886         for name, value in schema.items():
       
   887             ref_value = reference.get(name, None)
       
   888             if ref_value is None:
       
   889                 return False
       
   890             result = CompareSchema(value, ref_value)
       
   891             if not result:
       
   892                 return result
       
   893         return True
       
   894     elif isinstance(schema, FunctionType):
       
   895         if not isinstance(reference, FunctionType) or schema.__name__ != reference.__name__:
       
   896             return False
       
   897         else:
       
   898             return True
       
   899     return schema == reference
       
   900     
       
   901 #-------------------------------------------------------------------------------
       
   902 #                       Base class for XSD schema extraction
       
   903 #-------------------------------------------------------------------------------
       
   904 
       
   905 
       
   906 class XSDClassFactory(ClassFactory):
       
   907 
       
   908     def __init__(self, document, debug = False):
       
   909         ClassFactory.__init__(self, document, debug)
       
   910         self.Namespaces["xml"] = {
       
   911             "lang": {
       
   912                 "type": SYNTAXATTRIBUTE, 
       
   913                 "extract": {
       
   914                     "default": GenerateModelNameExtraction("lang", LANGUAGE_model)
       
   915                 }
       
   916             }
       
   917         }
       
   918         self.Namespaces["xsi"] = {
       
   919             "noNamespaceSchemaLocation": {
       
   920                 "type": SYNTAXATTRIBUTE, 
       
   921                 "extract": {
       
   922                     "default": NotSupportedYet("noNamespaceSchemaLocation")
       
   923                 }
       
   924             },
       
   925             "nil": {
       
   926                 "type": SYNTAXATTRIBUTE, 
       
   927                 "extract": {
       
   928                     "default": NotSupportedYet("nil")
       
   929                 }
       
   930             },
       
   931             "schemaLocation": {
       
   932                 "type": SYNTAXATTRIBUTE, 
       
   933                 "extract": {
       
   934                     "default": NotSupportedYet("schemaLocation")
       
   935                 }
       
   936             },
       
   937             "type": {
       
   938                 "type": SYNTAXATTRIBUTE, 
       
   939                 "extract": {
       
   940                     "default": NotSupportedYet("type")
       
   941                 }
       
   942             }
       
   943         }
       
   944         
       
   945     def ParseSchema(self):
       
   946         schema = self.Document.childNodes[0]
       
   947         for qualified_name, attr in schema._attrs.items():
       
   948             value = GetAttributeValue(attr)
       
   949             if value == "http://www.w3.org/2001/XMLSchema":
       
   950                 namespace, name = DecomposeQualifiedName(qualified_name)
       
   951                 if namespace == "xmlns":
       
   952                     self.DefinedNamespaces["http://www.w3.org/2001/XMLSchema"] = name
       
   953                     self.SchemaNamespace = name
       
   954                 else:
       
   955                     self.DefinedNamespaces["http://www.w3.org/2001/XMLSchema"] = self.SchemaNamespace
       
   956                 self.Namespaces[self.SchemaNamespace] = XSD_NAMESPACE
       
   957         self.Schema = XSD_NAMESPACE["schema"]["extract"]["default"](self, schema)
       
   958         ReduceSchema(self, self.Schema[1], self.Schema[2])
       
   959 
       
   960     def FindSchemaElement(self, element_name, element_type):
       
   961         namespace, name = DecomposeQualifiedName(element_name)
       
   962         element = self.GetQualifiedNameInfos(name, namespace, True)
       
   963         if element is None and namespace == self.TargetNamespace and name not in self.CurrentCompilations:
       
   964             self.CurrentCompilations.append(name)
       
   965             element = self.CreateSchemaElement(name, element_type)
       
   966             self.CurrentCompilations.pop(-1)
       
   967             if element is not None:
       
   968                 self.Namespaces[self.TargetNamespace][name] = element
       
   969         if element is None:
       
   970             if name in self.CurrentCompilations:
       
   971                 if self.Debug:
       
   972                     print "Warning : \"%s\" is circular referenced!" % element_name
       
   973                 return element_name
       
   974             else:
       
   975                 raise ValueError("\"%s\" isn't defined!" % element_name)
       
   976         if element["type"] != element_type:
       
   977             raise ValueError("\"%s\" isn't a group!" % element_name)
       
   978         return element
       
   979     
       
   980     def CreateSchemaElement(self, element_name, element_type):
       
   981         for type, attributes, elements in self.Schema[2]:
       
   982             namespace, name = DecomposeQualifiedName(type)
       
   983             if attributes.has_key("name") and attributes["name"] == element_name:
       
   984                 element_infos = None
       
   985                 if element_type == ATTRIBUTE and name == "attribute":
       
   986                     element_infos = ReduceAttribute(self, attributes, elements)
       
   987                 elif element_type == ELEMENT and name == "element":
       
   988                     element_infos = ReduceElement(self, attributes, elements)
       
   989                 elif element_type == ATTRIBUTESGROUP and name == "attributeGroup":
       
   990                     element_infos = ReduceAttributeGroup(self, attributes, elements)
       
   991                 elif element_type == ELEMENTSGROUP and name == "group":
       
   992                     element_infos = ReduceGroup(self, attributes, elements)
       
   993                 elif element_type == SIMPLETYPE and name == "simpleType":
       
   994                     element_infos = ReduceSimpleType(self, attributes, elements)
       
   995                 elif element_type == COMPLEXTYPE and name == "complexType":
       
   996                     element_infos = ReduceComplexType(self, attributes, elements)
       
   997                 if element_infos is not None:
       
   998                     self.Namespaces[self.TargetNamespace][element_name] = element_infos
       
   999                     return element_infos
       
  1000         return None
       
  1001 
       
  1002 """
       
  1003 This function opens the xsd file and generate the classes from the xml tree
       
  1004 """
       
  1005 def GenerateClassesFromXSD(filename, declare = False):
       
  1006     xsdfile = open(filename, 'r')
       
  1007     factory = XSDClassFactory(minidom.parse(xsdfile))
       
  1008     xsdfile.close()
       
  1009     factory.ParseSchema()
       
  1010     return GenerateClasses(factory, declare)
       
  1011 
       
  1012 """
       
  1013 This function generate the classes from the xsd given as a string
       
  1014 """
       
  1015 def GenerateClassesFromXSDstring(xsdstring, declare = False):
       
  1016     factory = XSDClassFactory(minidom.parseString(xsdstring))
       
  1017     factory.ParseSchema()
       
  1018     return GenerateClasses(factory, declare)
       
  1019 
       
  1020 
       
  1021 #-------------------------------------------------------------------------------
       
  1022 #                           XSD schema syntax elements
       
  1023 #-------------------------------------------------------------------------------
       
  1024 
       
  1025 XSD_NAMESPACE = {
       
  1026 
       
  1027 #-------------------------------------------------------------------------------
       
  1028 #                           Syntax elements definition
       
  1029 #-------------------------------------------------------------------------------
       
  1030 
       
  1031     "all": {"struct": """
       
  1032         <all
       
  1033           id = ID
       
  1034           maxOccurs = 1 : 1
       
  1035           minOccurs = (0 | 1) : 1
       
  1036           {any attributes with non-schema namespace . . .}>
       
  1037           Content: (annotation?, element*)
       
  1038         </all>""",
       
  1039         "type": SYNTAXELEMENT, 
       
  1040         "extract": {
       
  1041             "default": GenerateElement("all", ["id", "maxOccurs", "minOccurs"], 
       
  1042                 re.compile("((?:annotation )?(?:element )*)"))
       
  1043         },
       
  1044         "reduce": ReduceAll
       
  1045     },
       
  1046 
       
  1047     "annotation": {"struct": """
       
  1048         <annotation
       
  1049           id = ID
       
  1050           {any attributes with non-schema namespace . . .}>
       
  1051           Content: (appinfo | documentation)*
       
  1052         </annotation>""",
       
  1053         "type": SYNTAXELEMENT, 
       
  1054         "extract": {
       
  1055             "default": GenerateElement("annotation", ["id"], 
       
  1056                 re.compile("((?:app_info |documentation )*)"))
       
  1057         },
       
  1058         "reduce": ReduceAnnotation
       
  1059     },
       
  1060 
       
  1061     "any": {"struct": """
       
  1062         <any
       
  1063           id = ID
       
  1064           maxOccurs = (nonNegativeInteger | unbounded)  : 1
       
  1065           minOccurs = nonNegativeInteger : 1
       
  1066           namespace = ((##any | ##other) | List of (anyURI | (##targetNamespace | ##local)) )  : ##any
       
  1067           processContents = (lax | skip | strict) : strict
       
  1068           {any attributes with non-schema namespace . . .}>
       
  1069           Content: (annotation?)
       
  1070         </any>""",
       
  1071         "type": SYNTAXELEMENT, 
       
  1072         "extract": {
       
  1073             "default": GenerateElement("any", 
       
  1074                 ["id", "maxOccurs", "minOccurs", "namespace", "processContents"], 
       
  1075                 re.compile("((?:annotation )?(?:simpleType )*)"))
       
  1076         },
       
  1077         "reduce": ReduceAny
       
  1078     },
       
  1079 
       
  1080     "anyAttribute": {"struct": """
       
  1081         <anyAttribute
       
  1082           id = ID
       
  1083           namespace = ((##any | ##other) | List of (anyURI | (##targetNamespace | ##local)) )  : ##any
       
  1084           processContents = (lax | skip | strict) : strict
       
  1085           {any attributes with non-schema namespace . . .}>
       
  1086           Content: (annotation?)
       
  1087         </anyAttribute>""",
       
  1088         "type": SYNTAXELEMENT, 
       
  1089         "extract": {
       
  1090             "default": GenerateElement("anyAttribute",
       
  1091                 ["id", "namespace", "processContents"], ONLY_ANNOTATION)
       
  1092         },
       
  1093         "reduce": ReduceAnyAttribute
       
  1094     },
       
  1095 
       
  1096     "appinfo": {"struct": """
       
  1097         <appinfo
       
  1098           source = anyURI
       
  1099           {any attributes with non-schema namespace . . .}>
       
  1100           Content: ({any})*
       
  1101         </appinfo>""",
       
  1102         "type": SYNTAXELEMENT, 
       
  1103         "extract": {
       
  1104             "default": GenerateElement("appinfo", ["source"], re.compile("(.*)"), True)
       
  1105         },
       
  1106         "reduce": ReduceAppInfo
       
  1107     },
       
  1108 
       
  1109     "attribute": {"struct": """
       
  1110         <attribute
       
  1111           default = string
       
  1112           fixed = string
       
  1113           form = (qualified | unqualified)
       
  1114           id = ID
       
  1115           name = NCName
       
  1116           ref = QName
       
  1117           type = QName
       
  1118           use = (optional | prohibited | required) : optional
       
  1119           {any attributes with non-schema namespace . . .}>
       
  1120           Content: (annotation?, simpleType?)
       
  1121         </attribute>""",
       
  1122         "type": SYNTAXELEMENT, 
       
  1123         "extract": {
       
  1124             "default": GenerateElement("attribute", 
       
  1125                 ["default", "fixed", "form", "id", "name", "ref", "type", "use"], 
       
  1126                 re.compile("((?:annotation )?(?:simpleType )?)")),
       
  1127             "schema": GenerateElement("attribute", 
       
  1128                 ["default", "fixed", "form", "id", "name", "type"], 
       
  1129                 re.compile("((?:annotation )?(?:simpleType )?)"))
       
  1130         },
       
  1131         "reduce": ReduceAttribute
       
  1132     },
       
  1133 
       
  1134     "attributeGroup": {"struct": """
       
  1135         <attributeGroup
       
  1136           id = ID
       
  1137           name = NCName
       
  1138           ref = QName
       
  1139           {any attributes with non-schema namespace . . .}>
       
  1140           Content: (annotation?, ((attribute | attributeGroup)*, anyAttribute?))
       
  1141         </attributeGroup>""",
       
  1142         "type": SYNTAXELEMENT, 
       
  1143         "extract": {
       
  1144             "default": GenerateElement("attributeGroup", 
       
  1145                 ["id", "ref"], ONLY_ANNOTATION),
       
  1146             "schema": GenerateElement("attributeGroup",
       
  1147                 ["id", "name"], 
       
  1148                 re.compile("((?:annotation )?(?:(?:attribute |attributeGroup )*(?:anyAttribute )?))"))
       
  1149         },
       
  1150         "reduce": ReduceAttributeGroup
       
  1151     },
       
  1152 
       
  1153     "choice": {"struct": """
       
  1154         <choice
       
  1155           id = ID
       
  1156           maxOccurs = (nonNegativeInteger | unbounded)  : 1
       
  1157           minOccurs = nonNegativeInteger : 1
       
  1158           {any attributes with non-schema namespace . . .}>
       
  1159           Content: (annotation?, (element | group | choice | sequence | any)*)
       
  1160         </choice>""",
       
  1161         "type": SYNTAXELEMENT, 
       
  1162         "extract": {
       
  1163             "default": GenerateElement("choice", ["id", "maxOccurs", "minOccurs"], 
       
  1164                 re.compile("((?:annotation )?(?:element |group |choice |sequence |any )*)"))
       
  1165         },
       
  1166         "reduce": ReduceChoice
       
  1167     },
       
  1168 
       
  1169     "complexContent": {"struct": """
       
  1170         <complexContent
       
  1171           id = ID
       
  1172           mixed = boolean
       
  1173           {any attributes with non-schema namespace . . .}>
       
  1174           Content: (annotation?, (restriction | extension))
       
  1175         </complexContent>""",
       
  1176         "type": SYNTAXELEMENT, 
       
  1177         "extract": {
       
  1178             "default": GenerateElement("complexContent", ["id", "mixed"], 
       
  1179                 re.compile("((?:annotation )?(?:restriction |extension ))"))
       
  1180         },
       
  1181         "reduce": ReduceComplexContent
       
  1182     },
       
  1183 
       
  1184     "complexType": {"struct": """
       
  1185         <complexType
       
  1186           abstract = boolean : false
       
  1187           block = (#all | List of (extension | restriction))
       
  1188           final = (#all | List of (extension | restriction))
       
  1189           id = ID
       
  1190           mixed = boolean : false
       
  1191           name = NCName
       
  1192           {any attributes with non-schema namespace . . .}>
       
  1193           Content: (annotation?, (simpleContent | complexContent | ((group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?))))
       
  1194         </complexType>""",
       
  1195         "type": SYNTAXELEMENT, 
       
  1196         "extract": {
       
  1197             "default": GenerateElement("complexType", 
       
  1198                 ["abstract", "block", "final", "id", "mixed", "name"], 
       
  1199                 re.compile("((?:annotation )?(?:simpleContent |complexContent |(?:(?:group |all |choice |sequence )?(?:(?:attribute |attributeGroup )*(?:anyAttribute )?))))"))
       
  1200         },
       
  1201         "reduce": ReduceComplexType
       
  1202     },
       
  1203 
       
  1204     "documentation": {"struct" : """
       
  1205         <documentation
       
  1206           source = anyURI
       
  1207           xml:lang = language
       
  1208           {any attributes with non-schema namespace . . .}>
       
  1209           Content: ({any})*
       
  1210         </documentation>""",
       
  1211         "type": SYNTAXELEMENT, 
       
  1212         "extract": {
       
  1213             "default": GenerateElement("documentation", 
       
  1214                 ["source", "lang"], re.compile("(.*)"), True)
       
  1215         },
       
  1216         "reduce": ReduceDocumentation
       
  1217     },
       
  1218 
       
  1219     "element": {"struct": """
       
  1220         <element
       
  1221           abstract = boolean : false
       
  1222           block = (#all | List of (extension | restriction | substitution))
       
  1223           default = string
       
  1224           final = (#all | List of (extension | restriction))
       
  1225           fixed = string
       
  1226           form = (qualified | unqualified)
       
  1227           id = ID
       
  1228           maxOccurs = (nonNegativeInteger | unbounded)  : 1
       
  1229           minOccurs = nonNegativeInteger : 1
       
  1230           name = NCName
       
  1231           nillable = boolean : false
       
  1232           ref = QName
       
  1233           substitutionGroup = QName
       
  1234           type = QName
       
  1235           {any attributes with non-schema namespace . . .}>
       
  1236           Content: (annotation?, ((simpleType | complexType)?, (unique | key | keyref)*))
       
  1237         </element>""",
       
  1238         "type": SYNTAXELEMENT, 
       
  1239         "extract": {
       
  1240             "default": GenerateElement("element", 
       
  1241                 ["abstract", "block", "default", "final", "fixed", "form", "id", "maxOccurs", "minOccurs", "name", "nillable", "ref", "substitutionGroup", "type"], 
       
  1242                 re.compile("((?:annotation )?(?:simpleType |complexType )?(?:unique |key |keyref )*)")),
       
  1243             "schema": GenerateElement("element", 
       
  1244                 ["abstract", "block", "default", "final", "fixed", "form", "id", "name", "nillable", "substitutionGroup", "type"], 
       
  1245                 re.compile("((?:annotation )?(?:simpleType |complexType )?(?:unique |key |keyref )*)"))
       
  1246         },
       
  1247         "reduce": ReduceElement
       
  1248     },
       
  1249 
       
  1250     "enumeration": {"struct": """
       
  1251         <enumeration
       
  1252           id = ID
       
  1253           value = anySimpleType
       
  1254           {any attributes with non-schema namespace . . .}>
       
  1255           Content: (annotation?)
       
  1256         </enumeration>""",
       
  1257         "type": SYNTAXELEMENT, 
       
  1258         "extract": {
       
  1259             "default": GenerateElement("enumeration", ["id", "value"], ONLY_ANNOTATION)
       
  1260         },
       
  1261         "reduce": GenerateFacetReducing("enumeration", False)
       
  1262     },
       
  1263 
       
  1264     "extension": {"struct": """
       
  1265         <extension
       
  1266           base = QName
       
  1267           id = ID
       
  1268           {any attributes with non-schema namespace . . .}>
       
  1269           Content: (annotation?, ((group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?)))
       
  1270         </extension>""",
       
  1271         "type": SYNTAXELEMENT, 
       
  1272         "extract": {
       
  1273             "default": GenerateElement("extension", ["base", "id"], 
       
  1274                 re.compile("((?:annotation )?(?:(?:attribute |attributeGroup )*(?:anyAttribute )?))")),
       
  1275             "complexContent": GenerateElement("extension", ["base", "id"], 
       
  1276                 re.compile("((?:annotation )?(?:group |all |choice |sequence )?(?:(?:attribute |attributeGroup )*(?:anyAttribute )?))"))
       
  1277         },
       
  1278         "reduce": ReduceExtension
       
  1279     },
       
  1280 
       
  1281     "field": {"struct": """
       
  1282         <field
       
  1283           id = ID
       
  1284           xpath = a subset of XPath expression, see below
       
  1285           {any attributes with non-schema namespace . . .}>
       
  1286           Content: (annotation?)
       
  1287         </field>""",
       
  1288         "type": SYNTAXELEMENT, 
       
  1289         "extract": {
       
  1290             "default": GenerateElement("field", ["id", "xpath"], ONLY_ANNOTATION)
       
  1291         },
       
  1292         "reduce": ReduceField
       
  1293     },
       
  1294 
       
  1295     "fractionDigits": {"struct": """
       
  1296         <fractionDigits
       
  1297           fixed = boolean : false
       
  1298           id = ID
       
  1299           value = nonNegativeInteger
       
  1300           {any attributes with non-schema namespace . . .}>
       
  1301           Content: (annotation?)
       
  1302         </fractionDigits>""",
       
  1303         "type": SYNTAXELEMENT, 
       
  1304         "extract": {
       
  1305             "default": GenerateElement("fractionDigits", 
       
  1306                 ["fixed", "id", "value"], ONLY_ANNOTATION)
       
  1307         },
       
  1308         "reduce": GenerateFacetReducing("fractionDigits", True)
       
  1309     },
       
  1310 
       
  1311     "group": {"struct": """
       
  1312         <group
       
  1313           id = ID
       
  1314           maxOccurs = (nonNegativeInteger | unbounded)  : 1
       
  1315           minOccurs = nonNegativeInteger : 1
       
  1316           name = NCName
       
  1317           ref = QName
       
  1318           {any attributes with non-schema namespace . . .}>
       
  1319           Content: (annotation?, (all | choice | sequence)?)
       
  1320         </group>""",
       
  1321         "type": SYNTAXELEMENT, 
       
  1322         "extract": {
       
  1323             "default": GenerateElement("group",
       
  1324                 ["id", "maxOccurs", "minOccurs", "ref"], 
       
  1325                 re.compile("((?:annotation )?(?:all |choice |sequence )?)")),
       
  1326             "schema": GenerateElement("group",
       
  1327                 ["id", "name"], 
       
  1328                 re.compile("((?:annotation )?(?:all |choice |sequence )?)"))
       
  1329         },
       
  1330         "reduce": ReduceGroup
       
  1331     },
       
  1332 
       
  1333     "import": {"struct": """
       
  1334         <import
       
  1335           id = ID
       
  1336           namespace = anyURI
       
  1337           schemaLocation = anyURI
       
  1338           {any attributes with non-schema namespace . . .}>
       
  1339           Content: (annotation?)
       
  1340         </import>""",
       
  1341         "type": SYNTAXELEMENT, 
       
  1342         "extract": {
       
  1343             "default": GenerateElement("import",
       
  1344                 ["id", "namespace", "schemaLocation"], ONLY_ANNOTATION)
       
  1345         },
       
  1346         "reduce": ReduceImport
       
  1347     },
       
  1348 
       
  1349     "include": {"struct": """
       
  1350         <include
       
  1351           id = ID
       
  1352           schemaLocation = anyURI
       
  1353           {any attributes with non-schema namespace . . .}>
       
  1354           Content: (annotation?)
       
  1355         </include>""",
       
  1356         "type": SYNTAXELEMENT, 
       
  1357         "extract": {
       
  1358             "default": GenerateElement("include",
       
  1359                 ["id", "schemaLocation"], ONLY_ANNOTATION)
       
  1360         },
       
  1361         "reduce": ReduceInclude
       
  1362     },
       
  1363 
       
  1364     "key": {"struct": """
       
  1365         <key
       
  1366           id = ID
       
  1367           name = NCName
       
  1368           {any attributes with non-schema namespace . . .}>
       
  1369           Content: (annotation?, (selector, field+))
       
  1370         </key>""",
       
  1371         "type": SYNTAXELEMENT, 
       
  1372         "extract": {
       
  1373             "default": GenerateElement("key", ["id", "name"], 
       
  1374                 re.compile("((?:annotation )?(?:selector |(?:field )+))"))
       
  1375         },
       
  1376         "reduce": ReduceKey
       
  1377     },
       
  1378 
       
  1379     "keyref": {"struct": """
       
  1380         <keyref
       
  1381           id = ID
       
  1382           name = NCName
       
  1383           refer = QName
       
  1384           {any attributes with non-schema namespace . . .}>
       
  1385           Content: (annotation?, (selector, field+))
       
  1386         </keyref>""",
       
  1387         "type": SYNTAXELEMENT, 
       
  1388         "extract": {
       
  1389             "default": GenerateElement("keyref", ["id", "name", "refer"], 
       
  1390                 re.compile("((?:annotation )?(?:selector |(?:field )+))"))
       
  1391         },
       
  1392         "reduce": ReduceKeyRef
       
  1393     },
       
  1394 
       
  1395     "length": {"struct" : """
       
  1396         <length
       
  1397           fixed = boolean : false
       
  1398           id = ID
       
  1399           value = nonNegativeInteger
       
  1400           {any attributes with non-schema namespace . . .}>
       
  1401           Content: (annotation?)
       
  1402         </length>""",
       
  1403         "type": SYNTAXELEMENT, 
       
  1404         "extract": {
       
  1405             "default": GenerateElement("length", 
       
  1406                 ["fixed", "id", "value"], ONLY_ANNOTATION)
       
  1407         },
       
  1408         "reduce": GenerateFacetReducing("length", True)
       
  1409     },
       
  1410 
       
  1411     "list": {"struct": """
       
  1412         <list
       
  1413           id = ID
       
  1414           itemType = QName
       
  1415           {any attributes with non-schema namespace . . .}>
       
  1416           Content: (annotation?, simpleType?)
       
  1417         </list>""",
       
  1418         "type": SYNTAXELEMENT, 
       
  1419         "extract": {
       
  1420             "default": GenerateElement("list", ["id", "itemType"], 
       
  1421                 re.compile("((?:annotation )?(?:simpleType )?)$"))
       
  1422         },
       
  1423         "reduce": ReduceList
       
  1424     },
       
  1425 
       
  1426     "maxExclusive": {"struct": """
       
  1427         <maxInclusive
       
  1428           fixed = boolean : false
       
  1429           id = ID
       
  1430           value = anySimpleType
       
  1431           {any attributes with non-schema namespace . . .}>
       
  1432           Content: (annotation?)
       
  1433         </maxInclusive>""",
       
  1434         "type": SYNTAXELEMENT, 
       
  1435         "extract": {
       
  1436             "default": GenerateElement("maxExclusive",
       
  1437                 ["fixed", "id", "value"], ONLY_ANNOTATION)
       
  1438         },
       
  1439         "reduce": GenerateFacetReducing("maxExclusive", True)
       
  1440     },
       
  1441 
       
  1442     "maxInclusive": {"struct": """
       
  1443         <maxExclusive
       
  1444           fixed = boolean : false
       
  1445           id = ID
       
  1446           value = anySimpleType
       
  1447           {any attributes with non-schema namespace . . .}>
       
  1448           Content: (annotation?)
       
  1449         </maxExclusive>""",
       
  1450         "type": SYNTAXELEMENT, 
       
  1451         "extract": {
       
  1452             "default": GenerateElement("maxInclusive", 
       
  1453                 ["fixed", "id", "value"], ONLY_ANNOTATION)
       
  1454         },
       
  1455         "reduce": GenerateFacetReducing("maxInclusive", True)
       
  1456     },
       
  1457 
       
  1458     "maxLength": {"struct": """
       
  1459         <maxLength
       
  1460           fixed = boolean : false
       
  1461           id = ID
       
  1462           value = nonNegativeInteger
       
  1463           {any attributes with non-schema namespace . . .}>
       
  1464           Content: (annotation?)
       
  1465         </maxLength>""",
       
  1466         "type": SYNTAXELEMENT, 
       
  1467         "extract": {
       
  1468             "default": GenerateElement("maxLength", 
       
  1469                 ["fixed", "id", "value"], ONLY_ANNOTATION)
       
  1470         },
       
  1471         "reduce": GenerateFacetReducing("maxLength", True)
       
  1472     },
       
  1473 
       
  1474     "minExclusive": {"struct": """
       
  1475         <minExclusive
       
  1476           fixed = boolean : false
       
  1477           id = ID
       
  1478           value = anySimpleType
       
  1479           {any attributes with non-schema namespace . . .}>
       
  1480           Content: (annotation?)
       
  1481         </minExclusive>""",
       
  1482         "type": SYNTAXELEMENT, 
       
  1483         "extract": {
       
  1484             "default": GenerateElement("minExclusive", 
       
  1485                 ["fixed", "id", "value"], ONLY_ANNOTATION)
       
  1486         },
       
  1487         "reduce": GenerateFacetReducing("minExclusive", True)
       
  1488     },
       
  1489 
       
  1490     "minInclusive": {"struct": """
       
  1491         <minInclusive
       
  1492           fixed = boolean : false
       
  1493           id = ID
       
  1494           value = anySimpleType
       
  1495           {any attributes with non-schema namespace . . .}>
       
  1496           Content: (annotation?)
       
  1497         </minInclusive>""",
       
  1498         "type": SYNTAXELEMENT, 
       
  1499         "extract": {
       
  1500             "default": GenerateElement("minInclusive", 
       
  1501                 ["fixed", "id", "value"], ONLY_ANNOTATION)
       
  1502         },
       
  1503         "reduce": GenerateFacetReducing("minInclusive", True)
       
  1504     },
       
  1505 
       
  1506     "minLength": {"struct": """
       
  1507         <minLength
       
  1508           fixed = boolean : false
       
  1509           id = ID
       
  1510           value = nonNegativeInteger
       
  1511           {any attributes with non-schema namespace . . .}>
       
  1512           Content: (annotation?)
       
  1513         </minLength>""",
       
  1514         "type": SYNTAXELEMENT, 
       
  1515         "extract": {
       
  1516             "default": GenerateElement("minLength",
       
  1517                 ["fixed", "id", "value"], ONLY_ANNOTATION)
       
  1518         },
       
  1519         "reduce": GenerateFacetReducing("minLength", True)
       
  1520     },
       
  1521 
       
  1522     "pattern": {"struct": """
       
  1523         <pattern
       
  1524           id = ID
       
  1525           value = string
       
  1526           {any attributes with non-schema namespace . . .}>
       
  1527           Content: (annotation?)
       
  1528         </pattern>""",
       
  1529         "type": SYNTAXELEMENT, 
       
  1530         "extract": {
       
  1531             "default": GenerateElement("pattern", ["id", "value"], ONLY_ANNOTATION)
       
  1532         },
       
  1533         "reduce": GenerateFacetReducing("pattern", False)
       
  1534     },
       
  1535 
       
  1536     "redefine": {"struct": """
       
  1537         <redefine
       
  1538           id = ID
       
  1539           schemaLocation = anyURI
       
  1540           {any attributes with non-schema namespace . . .}>
       
  1541           Content: (annotation | (simpleType | complexType | group | attributeGroup))*
       
  1542         </redefine>""",
       
  1543         "type": SYNTAXELEMENT, 
       
  1544         "extract": {
       
  1545             "default": GenerateElement("refine", ["id", "schemaLocation"], 
       
  1546                 re.compile("((?:annotation |(?:simpleType |complexType |group |attributeGroup ))*)"))
       
  1547         },
       
  1548         "reduce": ReduceRedefine
       
  1549     },
       
  1550 
       
  1551     "restriction": {"struct": """
       
  1552         <restriction
       
  1553           base = QName
       
  1554           id = ID
       
  1555           {any attributes with non-schema namespace . . .}>
       
  1556           Content: (annotation?, (group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?))
       
  1557         </restriction>""",
       
  1558         "type": SYNTAXELEMENT, 
       
  1559         "extract": {
       
  1560             "default": GenerateElement("restriction", ["base", "id"], 
       
  1561                 re.compile("((?:annotation )?(?:(?:simpleType )?(?:(?:minExclusive |minInclusive |maxExclusive |maxInclusive |totalDigits |fractionDigits |length |minLength |maxLength |enumeration |whiteSpace |pattern )*)))")),
       
  1562             "simpleContent": GenerateElement("restriction", ["base", "id"], 
       
  1563                 re.compile("((?:annotation )?(?:(?:simpleType )?(?:(?:minExclusive |minInclusive |maxExclusive |maxInclusive |totalDigits |fractionDigits |length |minLength |maxLength |enumeration |whiteSpace |pattern )*)?(?:(?:attribute |attributeGroup )*(?:anyAttribute )?)))")),
       
  1564             "complexContent": GenerateElement("restriction", ["base", "id"], 
       
  1565                 re.compile("((?:annotation )?(?:(?:simpleType )?(?:group |all |choice |sequence )?(?:(?:attribute |attributeGroup )*(?:anyAttribute )?)))")),
       
  1566         },
       
  1567         "reduce": ReduceRestriction
       
  1568     },
       
  1569 
       
  1570     "schema": {"struct": """
       
  1571         <schema
       
  1572           attributeFormDefault = (qualified | unqualified) : unqualified
       
  1573           blockDefault = (#all | List of (extension | restriction | substitution))  : ''
       
  1574           elementFormDefault = (qualified | unqualified) : unqualified
       
  1575           finalDefault = (#all | List of (extension | restriction | list | union))  : ''
       
  1576           id = ID
       
  1577           targetNamespace = anyURI
       
  1578           version = token
       
  1579           xml:lang = language
       
  1580           {any attributes with non-schema namespace . . .}>
       
  1581           Content: ((include | import | redefine | annotation)*, (((simpleType | complexType | group | attributeGroup) | element | attribute | notation), annotation*)*)
       
  1582         </schema>""",
       
  1583         "type": SYNTAXELEMENT, 
       
  1584         "extract": {
       
  1585             "default": GenerateElement("schema",
       
  1586                 ["attributeFormDefault", "blockDefault", "elementFormDefault", "finalDefault", "id", "targetNamespace", "version", "lang"], 
       
  1587                 re.compile("((?:include |import |redefine |annotation )*(?:(?:(?:simpleType |complexType |group |attributeGroup )|element |attribute |annotation )(?:annotation )*)*)"))
       
  1588         }
       
  1589     },
       
  1590 
       
  1591     "selector": {"struct": """
       
  1592         <selector
       
  1593           id = ID
       
  1594           xpath = a subset of XPath expression, see below
       
  1595           {any attributes with non-schema namespace . . .}>
       
  1596           Content: (annotation?)
       
  1597         </selector>""",
       
  1598         "type": SYNTAXELEMENT, 
       
  1599         "extract": {
       
  1600             "default": GenerateElement("selector", ["id", "xpath"], ONLY_ANNOTATION)
       
  1601         },
       
  1602         "reduce": ReduceSelector
       
  1603     },
       
  1604 
       
  1605     "sequence": {"struct": """
       
  1606         <sequence
       
  1607           id = ID
       
  1608           maxOccurs = (nonNegativeInteger | unbounded)  : 1
       
  1609           minOccurs = nonNegativeInteger : 1
       
  1610           {any attributes with non-schema namespace . . .}>
       
  1611           Content: (annotation?, (element | group | choice | sequence | any)*)
       
  1612         </sequence>""",
       
  1613         "type": SYNTAXELEMENT, 
       
  1614         "extract": {
       
  1615             "default": GenerateElement("sequence", ["id", "maxOccurs", "minOccurs"], 
       
  1616                 re.compile("((?:annotation )?(?:element |group |choice |sequence |any )*)"))
       
  1617         },
       
  1618         "reduce": ReduceSequence
       
  1619     },
       
  1620 
       
  1621     "simpleContent": {"struct" : """
       
  1622         <simpleContent
       
  1623           id = ID
       
  1624           {any attributes with non-schema namespace . . .}>
       
  1625           Content: (annotation?, (restriction | extension))
       
  1626         </simpleContent>""",
       
  1627         "type": SYNTAXELEMENT, 
       
  1628         "extract": {
       
  1629             "default": GenerateElement("simpleContent", ["id"], 
       
  1630                 re.compile("((?:annotation )?(?:restriction |extension ))"))
       
  1631         },
       
  1632         "reduce": ReduceSimpleContent
       
  1633     },
       
  1634 
       
  1635     "simpleType": {"struct" : """
       
  1636         <simpleType
       
  1637           final = (#all | List of (list | union | restriction))
       
  1638           id = ID
       
  1639           name = NCName
       
  1640           {any attributes with non-schema namespace . . .}>
       
  1641           Content: (annotation?, (restriction | list | union))
       
  1642         </simpleType>""",
       
  1643         "type": SYNTAXELEMENT, 
       
  1644         "extract": {
       
  1645             "default": GenerateElement("simpleType", ["final", "id", "name"], 
       
  1646                 re.compile("((?:annotation )?(?:restriction |list |union ))"))
       
  1647         },
       
  1648         "reduce": ReduceSimpleType
       
  1649     },
       
  1650 
       
  1651     "totalDigits": {"struct" : """
       
  1652         <totalDigits
       
  1653           fixed = boolean : false
       
  1654           id = ID
       
  1655           value = positiveInteger
       
  1656           {any attributes with non-schema namespace . . .}>
       
  1657           Content: (annotation?)
       
  1658         </totalDigits>""",
       
  1659         "type": SYNTAXELEMENT, 
       
  1660         "extract": {
       
  1661             "default": GenerateElement("totalDigits", 
       
  1662                 ["fixed", "id", "value"], ONLY_ANNOTATION),
       
  1663         },
       
  1664         "reduce": GenerateFacetReducing("totalDigits", True)
       
  1665     },
       
  1666 
       
  1667     "union": {"struct": """
       
  1668         <union
       
  1669           id = ID
       
  1670           memberTypes = List of QName
       
  1671           {any attributes with non-schema namespace . . .}>
       
  1672           Content: (annotation?, simpleType*)
       
  1673         </union>""",
       
  1674         "type": SYNTAXELEMENT, 
       
  1675         "extract": {
       
  1676             "default": GenerateElement("union", ["id", "memberTypes"], 
       
  1677                 re.compile("((?:annotation )?(?:simpleType )*)"))
       
  1678         },
       
  1679         "reduce": ReduceUnion
       
  1680     },
       
  1681 
       
  1682     "unique": {"struct": """
       
  1683         <unique
       
  1684           id = ID
       
  1685           name = NCName
       
  1686           {any attributes with non-schema namespace . . .}>
       
  1687           Content: (annotation?, (selector, field+))
       
  1688         </unique>""",
       
  1689         "type": SYNTAXELEMENT, 
       
  1690         "extract": {
       
  1691             "default": GenerateElement("unique", ["id", "name"], 
       
  1692                 re.compile("((?:annotation )?(?:selector |(?:field )+))"))
       
  1693         },
       
  1694         "reduce": ReduceUnique
       
  1695     },
       
  1696     
       
  1697     "whiteSpace": {"struct" : """
       
  1698         <whiteSpace
       
  1699           fixed = boolean : false
       
  1700           id = ID
       
  1701           value = (collapse | preserve | replace)
       
  1702           {any attributes with non-schema namespace . . .}>
       
  1703           Content: (annotation?)
       
  1704         </whiteSpace>""",
       
  1705         "type": SYNTAXELEMENT, 
       
  1706         "extract": {
       
  1707             "default": GenerateElement("whiteSpace", 
       
  1708                 ["fixed", "id", "value"], ONLY_ANNOTATION)
       
  1709         },
       
  1710         "reduce": GenerateFacetReducing("whiteSpace", True)
       
  1711     },
       
  1712 
       
  1713 #-------------------------------------------------------------------------------
       
  1714 #                       Syntax attributes definition
       
  1715 #-------------------------------------------------------------------------------
       
  1716 
       
  1717     "abstract": {
       
  1718         "type": SYNTAXATTRIBUTE, 
       
  1719         "extract": {
       
  1720             "default": GetBoolean
       
  1721         },
       
  1722         "default": {
       
  1723             "default": False
       
  1724         }
       
  1725     },
       
  1726 
       
  1727     "attributeFormDefault": {
       
  1728         "type": SYNTAXATTRIBUTE, 
       
  1729         "extract": {
       
  1730             "default": GenerateEnumeratedExtraction("member attributeFormDefault", ["qualified", "unqualified"])
       
  1731         },
       
  1732         "default": {
       
  1733             "default": "unqualified"
       
  1734         }
       
  1735     },
       
  1736     
       
  1737     "base": {
       
  1738         "type": SYNTAXATTRIBUTE, 
       
  1739         "extract": {
       
  1740             "default": GenerateModelNameExtraction("member base", QName_model)
       
  1741         }
       
  1742     },
       
  1743     
       
  1744     "block": {
       
  1745         "type": SYNTAXATTRIBUTE, 
       
  1746         "extract": {
       
  1747             "default": GenerateGetList("block", ["restriction", "extension", "substitution"])
       
  1748         }
       
  1749     },
       
  1750     
       
  1751     "blockDefault": {
       
  1752         "type": SYNTAXATTRIBUTE, 
       
  1753         "extract": {
       
  1754             "default": GenerateGetList("block", ["restriction", "extension", "substitution"])
       
  1755         },
       
  1756         "default": {
       
  1757             "default": ""
       
  1758         }
       
  1759     },
       
  1760     
       
  1761     "default": {
       
  1762         "type": SYNTAXATTRIBUTE, 
       
  1763         "extract": {
       
  1764             "default": GetAttributeValue
       
  1765         }
       
  1766     },
       
  1767 
       
  1768     "elementFormDefault": {
       
  1769         "type": SYNTAXATTRIBUTE, 
       
  1770         "extract": {
       
  1771             "default": GenerateEnumeratedExtraction("member elementFormDefault", ["qualified", "unqualified"])
       
  1772         },
       
  1773         "default": {
       
  1774             "default": "unqualified"
       
  1775         }
       
  1776     },
       
  1777     
       
  1778     "final": {
       
  1779         "type": SYNTAXATTRIBUTE, 
       
  1780         "extract": {
       
  1781             "default": GenerateGetList("final", ["restriction", "extension", "substitution"]),
       
  1782             "simpleType": GenerateGetList("final", ["list", "union", "restriction"])
       
  1783         }
       
  1784     },
       
  1785 
       
  1786     "finalDefault": {
       
  1787         "type": SYNTAXATTRIBUTE, 
       
  1788         "extract": {
       
  1789             "default": GenerateGetList("finalDefault", ["restriction", "extension", "list", "union"])
       
  1790         },
       
  1791         "default": {
       
  1792             "default": ""
       
  1793         }
       
  1794     },
       
  1795     
       
  1796     "fixed": {
       
  1797         "type": SYNTAXATTRIBUTE, 
       
  1798         "extract": {
       
  1799             "default": GetBoolean,
       
  1800             "attribute": GetAttributeValue,
       
  1801             "element": GetAttributeValue
       
  1802         },
       
  1803         "default": {
       
  1804             "default": False,
       
  1805             "attribute": None,
       
  1806             "element": None
       
  1807         }
       
  1808     },
       
  1809 
       
  1810     "form": {
       
  1811         "type": SYNTAXATTRIBUTE, 
       
  1812         "extract": {
       
  1813             "default": GenerateEnumeratedExtraction("member form", ["qualified", "unqualified"])
       
  1814         }
       
  1815     },
       
  1816 
       
  1817     "id": {
       
  1818         "type": SYNTAXATTRIBUTE, 
       
  1819         "extract": {
       
  1820             "default": GenerateModelNameExtraction("member id", NCName_model)
       
  1821         }
       
  1822     },
       
  1823     
       
  1824     "itemType": {
       
  1825         "type": SYNTAXATTRIBUTE, 
       
  1826         "extract": {
       
  1827             "default": GenerateModelNameExtraction("member itemType", QName_model)
       
  1828         }
       
  1829     },
       
  1830 
       
  1831     "memberTypes": {
       
  1832         "type": SYNTAXATTRIBUTE, 
       
  1833         "extract": {
       
  1834             "default": GenerateModelNameListExtraction("member memberTypes", QNames_model)
       
  1835         },
       
  1836     },
       
  1837     
       
  1838     "maxOccurs": {
       
  1839         "type": SYNTAXATTRIBUTE, 
       
  1840         "extract": {
       
  1841             "default": GenerateLimitExtraction(),
       
  1842             "all": GenerateLimitExtraction(1, 1, False)
       
  1843         },
       
  1844         "default": {
       
  1845             "default": 1
       
  1846         }
       
  1847     },
       
  1848 
       
  1849     "minOccurs": {
       
  1850         "type": SYNTAXATTRIBUTE, 
       
  1851         "extract": {
       
  1852             "default": GenerateLimitExtraction(unbounded = False),
       
  1853             "all": GenerateLimitExtraction(0, 1, False)
       
  1854         },
       
  1855         "default": {
       
  1856             "default": 1
       
  1857         }
       
  1858     },
       
  1859 
       
  1860     "mixed": {
       
  1861         "type": SYNTAXATTRIBUTE, 
       
  1862         "extract": {
       
  1863             "default": GetBoolean
       
  1864         },
       
  1865         "default": {
       
  1866             "default": None,
       
  1867             "complexType": False
       
  1868         }
       
  1869     },
       
  1870     
       
  1871     "name": {
       
  1872         "type": SYNTAXATTRIBUTE, 
       
  1873         "extract": {
       
  1874             "default": GenerateModelNameExtraction("member name", NCName_model)
       
  1875         }
       
  1876     },
       
  1877     
       
  1878     "namespace": {
       
  1879         "type": SYNTAXATTRIBUTE, 
       
  1880         "extract": {
       
  1881             "default": GenerateModelNameExtraction("member namespace", URI_model),
       
  1882             "any": GetNamespaces
       
  1883         },
       
  1884         "default": {
       
  1885             "default": None,
       
  1886             "any": "##any"
       
  1887         }
       
  1888     },
       
  1889 
       
  1890     "nillable": {
       
  1891         "type": SYNTAXATTRIBUTE, 
       
  1892         "extract": {
       
  1893             "default": GetBoolean
       
  1894         },
       
  1895     },
       
  1896     
       
  1897     "processContents": {
       
  1898         "type": SYNTAXATTRIBUTE, 
       
  1899         "extract": {
       
  1900             "default": GenerateEnumeratedExtraction("member processContents", ["lax", "skip", "strict"])
       
  1901         },
       
  1902         "default": {
       
  1903             "default": "strict"
       
  1904         }
       
  1905     },
       
  1906     
       
  1907     "ref": {
       
  1908         "type": SYNTAXATTRIBUTE, 
       
  1909         "extract": {
       
  1910             "default": GenerateModelNameExtraction("member ref", QName_model)
       
  1911         }
       
  1912     },
       
  1913 
       
  1914     "refer": {
       
  1915         "type": SYNTAXATTRIBUTE,
       
  1916         "extract": {
       
  1917             "default": GenerateModelNameExtraction("member refer", QName_model)
       
  1918         }
       
  1919     },
       
  1920     
       
  1921     "schemaLocation": {
       
  1922         "type": SYNTAXATTRIBUTE, 
       
  1923         "extract": {
       
  1924             "default": GenerateModelNameExtraction("member schemaLocation", URI_model)
       
  1925         }
       
  1926     },
       
  1927     
       
  1928     "source": {
       
  1929         "type": SYNTAXATTRIBUTE,
       
  1930         "extract": {
       
  1931             "default": GenerateModelNameExtraction("member source", URI_model)
       
  1932         }
       
  1933     },
       
  1934     
       
  1935     "substitutionGroup": {
       
  1936         "type": SYNTAXATTRIBUTE, 
       
  1937         "extract": {
       
  1938             "default": GenerateModelNameExtraction("member substitutionGroup", QName_model)
       
  1939         }
       
  1940     },
       
  1941 
       
  1942     "targetNamespace": {
       
  1943         "type": SYNTAXATTRIBUTE, 
       
  1944         "extract": {
       
  1945             "default": GenerateModelNameExtraction("member targetNamespace", URI_model)
       
  1946         }
       
  1947     },
       
  1948     
       
  1949     "type": {
       
  1950         "type": SYNTAXATTRIBUTE, 
       
  1951         "extract": {
       
  1952             "default": GenerateModelNameExtraction("member type", QName_model)
       
  1953         }
       
  1954     },
       
  1955 
       
  1956     "use": {
       
  1957         "type": SYNTAXATTRIBUTE, 
       
  1958         "extract": {
       
  1959             "default": GenerateEnumeratedExtraction("member usage", ["required", "optional", "prohibited"])
       
  1960         },
       
  1961         "default": {
       
  1962             "default": "optional"
       
  1963         }
       
  1964     },
       
  1965 
       
  1966     "value": {
       
  1967         "type": SYNTAXATTRIBUTE, 
       
  1968         "extract": {
       
  1969             "default": GetAttributeValue,
       
  1970             "fractionDigits": GenerateIntegerExtraction(minInclusive=0),
       
  1971             "length": GenerateIntegerExtraction(minInclusive=0),
       
  1972             "maxLength": GenerateIntegerExtraction(minInclusive=0),
       
  1973             "minLength": GenerateIntegerExtraction(minInclusive=0),
       
  1974             "totalDigits": GenerateIntegerExtraction(minExclusive=0),
       
  1975             "whiteSpace": GenerateEnumeratedExtraction("value", ["collapse", "preserve", "replace"])
       
  1976         }
       
  1977     },
       
  1978 
       
  1979     "version": {
       
  1980         "type": SYNTAXATTRIBUTE,
       
  1981         "extract": {
       
  1982             "default": GetToken
       
  1983         }
       
  1984     },
       
  1985 
       
  1986     "xpath": {
       
  1987         "type": SYNTAXATTRIBUTE, 
       
  1988         "extract": {
       
  1989             "default": NotSupportedYet("xpath")
       
  1990         }
       
  1991     },
       
  1992     
       
  1993 #-------------------------------------------------------------------------------
       
  1994 #                           Simple types definition
       
  1995 #-------------------------------------------------------------------------------
       
  1996 
       
  1997     "string": {
       
  1998         "type": SIMPLETYPE,
       
  1999         "basename": "string",
       
  2000         "extract": GetAttributeValue,
       
  2001         "facets": STRING_FACETS,
       
  2002         "generate": GenerateSimpleTypeXMLText(lambda x : x),
       
  2003         "initial": lambda: "",
       
  2004         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2005     },
       
  2006 
       
  2007     "normalizedString": {
       
  2008         "type": SIMPLETYPE,
       
  2009         "basename": "normalizedString",
       
  2010         "extract": GetNormalizedString,
       
  2011         "facets": STRING_FACETS,
       
  2012         "generate": GenerateSimpleTypeXMLText(lambda x : x),
       
  2013         "initial": lambda: "",
       
  2014         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2015     },
       
  2016 
       
  2017     "token": {
       
  2018         "type": SIMPLETYPE,
       
  2019         "basename": "token",  
       
  2020         "extract": GetToken,
       
  2021         "facets": STRING_FACETS,
       
  2022         "generate": GenerateSimpleTypeXMLText(lambda x : x),
       
  2023         "initial": lambda: "",
       
  2024         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2025     },
       
  2026     
       
  2027     "base64Binary": {
       
  2028         "type": SIMPLETYPE, 
       
  2029         "basename": "base64Binary", 
       
  2030         "extract": NotSupportedYet("base64Binary"),
       
  2031         "facets": STRING_FACETS,
       
  2032         "generate": GenerateSimpleTypeXMLText(str),
       
  2033         "initial": lambda: 0,
       
  2034         "check": lambda x: isinstance(x, IntType)
       
  2035     },
       
  2036     
       
  2037     "hexBinary": {
       
  2038         "type": SIMPLETYPE,
       
  2039         "basename": "hexBinary", 
       
  2040         "extract": GetHexInteger,
       
  2041         "facets": STRING_FACETS,
       
  2042         "generate": GenerateSimpleTypeXMLText(lambda x: ("%."+str(int(round(len("%X"%x)/2.)*2))+"X")%x),
       
  2043         "initial": lambda: 0,
       
  2044         "check": lambda x: isinstance(x, IntType)
       
  2045     },
       
  2046 
       
  2047     "integer": {
       
  2048         "type": SIMPLETYPE,
       
  2049         "basename": "integer", 
       
  2050         "extract": GenerateIntegerExtraction(),
       
  2051         "facets": DECIMAL_FACETS,
       
  2052         "generate": GenerateSimpleTypeXMLText(str),
       
  2053         "initial": lambda: 0,
       
  2054         "check": lambda x: isinstance(x, IntType)
       
  2055     },
       
  2056     
       
  2057     "positiveInteger": {
       
  2058         "type": SIMPLETYPE,
       
  2059         "basename": "positiveInteger", 
       
  2060         "extract": GenerateIntegerExtraction(minExclusive=0),
       
  2061         "facets": DECIMAL_FACETS,
       
  2062         "generate": GenerateSimpleTypeXMLText(str),
       
  2063         "initial": lambda: 0,
       
  2064         "check": lambda x: isinstance(x, IntType)
       
  2065     },
       
  2066     
       
  2067     "negativeInteger": {
       
  2068         "type": SIMPLETYPE,
       
  2069         "basename": "negativeInteger",
       
  2070         "extract": GenerateIntegerExtraction(maxExclusive=0),
       
  2071         "facets": DECIMAL_FACETS,
       
  2072         "generate": GenerateSimpleTypeXMLText(str),
       
  2073         "initial": lambda: 0,
       
  2074         "check": lambda x: isinstance(x, IntType)
       
  2075     },
       
  2076     
       
  2077     "nonNegativeInteger": {
       
  2078         "type": SIMPLETYPE, 
       
  2079         "basename": "nonNegativeInteger", 
       
  2080         "extract": GenerateIntegerExtraction(minInclusive=0),
       
  2081         "facets": DECIMAL_FACETS,
       
  2082         "generate": GenerateSimpleTypeXMLText(str),
       
  2083         "initial": lambda: 0,
       
  2084         "check": lambda x: isinstance(x, IntType)
       
  2085     },
       
  2086     
       
  2087     "nonPositiveInteger": {
       
  2088         "type": SIMPLETYPE,
       
  2089         "basename": "nonPositiveInteger", 
       
  2090         "extract": GenerateIntegerExtraction(maxInclusive=0),
       
  2091         "facets": DECIMAL_FACETS,
       
  2092         "generate": GenerateSimpleTypeXMLText(str),
       
  2093         "initial": lambda: 0,
       
  2094         "check": lambda x: isinstance(x, IntType)
       
  2095     },
       
  2096     
       
  2097     "long": {
       
  2098         "type": SIMPLETYPE,
       
  2099         "basename": "long",
       
  2100         "extract": GenerateIntegerExtraction(minInclusive=-2**63,maxExclusive=2**63),
       
  2101         "facets": DECIMAL_FACETS,
       
  2102         "generate": GenerateSimpleTypeXMLText(str),
       
  2103         "initial": lambda: 0,
       
  2104         "check": lambda x: isinstance(x, IntType)
       
  2105     },
       
  2106     
       
  2107     "unsignedLong": {
       
  2108         "type": SIMPLETYPE,
       
  2109         "basename": "unsignedLong",
       
  2110         "extract": GenerateIntegerExtraction(minInclusive=0,maxExclusive=2**64),
       
  2111         "facets": DECIMAL_FACETS,
       
  2112         "generate": GenerateSimpleTypeXMLText(str),
       
  2113         "initial": lambda: 0,
       
  2114         "check": lambda x: isinstance(x, IntType)
       
  2115     },
       
  2116 
       
  2117     "int": {
       
  2118         "type": SIMPLETYPE,
       
  2119         "basename": "int",
       
  2120         "extract": GenerateIntegerExtraction(minInclusive=-2**31,maxExclusive=2**31),
       
  2121         "facets": DECIMAL_FACETS,
       
  2122         "generate": GenerateSimpleTypeXMLText(str),
       
  2123         "initial": lambda: 0,
       
  2124         "check": lambda x: isinstance(x, IntType)
       
  2125     },
       
  2126 
       
  2127     "unsignedInt": {
       
  2128         "type": SIMPLETYPE,
       
  2129         "basename": "unsignedInt",
       
  2130         "extract": GenerateIntegerExtraction(minInclusive=0,maxExclusive=2**32),
       
  2131         "facets": DECIMAL_FACETS,
       
  2132         "generate": GenerateSimpleTypeXMLText(str),
       
  2133         "initial": lambda: 0,
       
  2134         "check": lambda x: isinstance(x, IntType)
       
  2135     },
       
  2136 
       
  2137     "short": {
       
  2138         "type": SIMPLETYPE,
       
  2139         "basename": "short",
       
  2140         "extract": GenerateIntegerExtraction(minInclusive=-2**15,maxExclusive=2**15),
       
  2141         "facets": DECIMAL_FACETS,
       
  2142         "generate": GenerateSimpleTypeXMLText(str),
       
  2143         "initial": lambda: 0,
       
  2144         "check": lambda x: isinstance(x, IntType)
       
  2145     },
       
  2146 
       
  2147     "unsignedShort": {
       
  2148         "type": SIMPLETYPE,
       
  2149         "basename": "unsignedShort", 
       
  2150         "extract": GenerateIntegerExtraction(minInclusive=0,maxExclusive=2**16),
       
  2151         "facets": DECIMAL_FACETS,
       
  2152         "generate": GenerateSimpleTypeXMLText(str),
       
  2153         "initial": lambda: 0,
       
  2154         "check": lambda x: isinstance(x, IntType)
       
  2155     },
       
  2156 
       
  2157     "byte": {
       
  2158         "type": SIMPLETYPE,
       
  2159         "basename": "byte",
       
  2160         "extract": GenerateIntegerExtraction(minInclusive=-2**7,maxExclusive=2**7),
       
  2161         "facets": DECIMAL_FACETS,
       
  2162         "generate": GenerateSimpleTypeXMLText(str),
       
  2163         "initial": lambda: 0,
       
  2164         "check": lambda x: isinstance(x, IntType)
       
  2165     },
       
  2166 
       
  2167     "unsignedByte": {
       
  2168         "type": SIMPLETYPE,
       
  2169         "basename": "unsignedByte",
       
  2170         "extract": GenerateIntegerExtraction(minInclusive=0,maxExclusive=2**8),
       
  2171         "facets": DECIMAL_FACETS,
       
  2172         "generate": GenerateSimpleTypeXMLText(str),
       
  2173         "initial": lambda: 0,
       
  2174         "check": lambda x: isinstance(x, IntType)
       
  2175     },
       
  2176 
       
  2177     "decimal": {
       
  2178         "type": SIMPLETYPE,
       
  2179         "basename": "decimal",
       
  2180         "extract": GenerateFloatExtraction("decimal"),
       
  2181         "facets": DECIMAL_FACETS,
       
  2182         "generate": GenerateFloatXMLText(),
       
  2183         "initial": lambda: 0.,
       
  2184         "check": lambda x: isinstance(x, (IntType, FloatType))
       
  2185     },
       
  2186 
       
  2187     "float": {
       
  2188         "type": SIMPLETYPE,
       
  2189         "basename": "float",
       
  2190         "extract": GenerateFloatExtraction("float", ["INF", "-INF", "NaN"]),
       
  2191         "facets": NUMBER_FACETS,
       
  2192         "generate": GenerateFloatXMLText(["INF", "-INF", "NaN"]),
       
  2193         "initial": lambda: 0.,
       
  2194         "check": lambda x: {"INF" : True, "-INF" : True, "NaN" : True}.get(x, isinstance(x, (IntType, FloatType)))
       
  2195     },
       
  2196 
       
  2197     "double": {
       
  2198         "type": SIMPLETYPE,
       
  2199         "basename": "double",
       
  2200         "extract": GenerateFloatExtraction("double", ["INF", "-INF", "NaN"]),
       
  2201         "facets": NUMBER_FACETS,
       
  2202         "generate": GenerateFloatXMLText(["INF", "-INF", "NaN"]),
       
  2203         "initial": lambda: 0.,
       
  2204         "check": lambda x: {"INF" : True, "-INF" : True, "NaN" : True}.get(x, isinstance(x, (IntType, FloatType)))
       
  2205     },
       
  2206 
       
  2207     "boolean": {
       
  2208         "type": SIMPLETYPE,
       
  2209         "basename": "boolean",
       
  2210         "extract": GetBoolean,
       
  2211         "facets": GenerateDictFacets(["pattern", "whiteSpace"]),
       
  2212         "generate": GenerateSimpleTypeXMLText(lambda x:{True : "true", False : "false"}[x]),
       
  2213         "initial": lambda: False,
       
  2214         "check": lambda x: isinstance(x, BooleanType)
       
  2215     },	
       
  2216 
       
  2217     "duration": {
       
  2218         "type": SIMPLETYPE,
       
  2219         "basename": "duration",
       
  2220         "extract": NotSupportedYet("duration"),
       
  2221         "facets": NUMBER_FACETS,
       
  2222         "generate": GenerateSimpleTypeXMLText(str),
       
  2223         "initial": lambda: "",
       
  2224         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2225     },
       
  2226 
       
  2227     "dateTime": {
       
  2228         "type": SIMPLETYPE,
       
  2229         "basename": "dateTime",
       
  2230         "extract": GetDateTime,
       
  2231         "facets": NUMBER_FACETS,
       
  2232         "generate": GenerateSimpleTypeXMLText(datetime.datetime.isoformat),
       
  2233         "initial": lambda: datetime.datetime(1,1,1,0,0,0,0),
       
  2234         "check": lambda x: isinstance(x, datetime.datetime)
       
  2235     },
       
  2236 
       
  2237     "date": {
       
  2238         "type": SIMPLETYPE,
       
  2239         "basename": "date",
       
  2240         "extract": GetDate,
       
  2241         "facets": NUMBER_FACETS,
       
  2242         "generate": GenerateSimpleTypeXMLText(datetime.date.isoformat),
       
  2243         "initial": lambda: datetime.date(1,1,1),
       
  2244         "check": lambda x: isinstance(x, datetime.date)
       
  2245     },
       
  2246     
       
  2247     "time": {
       
  2248         "type": SIMPLETYPE,
       
  2249         "basename": "time",
       
  2250         "extract": GetTime,
       
  2251         "facets": NUMBER_FACETS,
       
  2252         "generate": GenerateSimpleTypeXMLText(datetime.time.isoformat),
       
  2253         "initial": lambda: datetime.time(0,0,0,0),
       
  2254         "check": lambda x: isinstance(x, datetime.time)
       
  2255     },
       
  2256 
       
  2257     "gYear": {
       
  2258         "type": SIMPLETYPE,
       
  2259         "basename": "gYear",
       
  2260         "extract": NotSupportedYet("gYear"),
       
  2261         "facets": NUMBER_FACETS,
       
  2262         "generate": GenerateSimpleTypeXMLText(str),
       
  2263         "initial": lambda: "",
       
  2264         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2265     },
       
  2266 
       
  2267     "gYearMonth": {
       
  2268         "type": SIMPLETYPE,
       
  2269         "basename": "gYearMonth",
       
  2270         "extract": NotSupportedYet("gYearMonth"),
       
  2271         "facets": NUMBER_FACETS,
       
  2272         "generate": GenerateSimpleTypeXMLText(str),
       
  2273         "initial": lambda: "",
       
  2274         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2275     },
       
  2276 
       
  2277     "gMonth": {
       
  2278         "type": SIMPLETYPE,
       
  2279         "basename": "gMonth",
       
  2280         "extract": NotSupportedYet("gMonth"),
       
  2281         "facets": NUMBER_FACETS,
       
  2282         "generate": GenerateSimpleTypeXMLText(str),
       
  2283         "initial": lambda: "",
       
  2284         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2285     },
       
  2286 
       
  2287     "gMonthDay": {
       
  2288         "type": SIMPLETYPE,
       
  2289         "basename": "gMonthDay",
       
  2290         "extract": NotSupportedYet("gMonthDay"),
       
  2291         "facets": NUMBER_FACETS,
       
  2292         "generate": GenerateSimpleTypeXMLText(str),
       
  2293         "initial": lambda: "",
       
  2294         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2295     },
       
  2296 
       
  2297     "gDay": {
       
  2298         "type": SIMPLETYPE,
       
  2299         "basename": "gDay",
       
  2300         "extract": NotSupportedYet("gDay"),
       
  2301         "facets": NUMBER_FACETS,
       
  2302         "generate": GenerateSimpleTypeXMLText(str),
       
  2303         "initial": lambda: "",
       
  2304         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2305     },
       
  2306 
       
  2307     "Name": {
       
  2308         "type": SIMPLETYPE,
       
  2309         "basename": "Name",
       
  2310         "extract": GenerateModelNameExtraction("Name", Name_model),
       
  2311         "facets": STRING_FACETS,
       
  2312         "generate": GenerateSimpleTypeXMLText(lambda x: x),
       
  2313         "initial": lambda: "",
       
  2314         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2315     },
       
  2316     
       
  2317     "QName": {
       
  2318         "type": SIMPLETYPE,
       
  2319         "basename": "QName",
       
  2320         "extract": GenerateModelNameExtraction("QName", QName_model),
       
  2321         "facets": STRING_FACETS,
       
  2322         "generate": GenerateSimpleTypeXMLText(lambda x: x),
       
  2323         "initial": lambda: "",
       
  2324         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2325     },
       
  2326 
       
  2327     "NCName": {
       
  2328         "type": SIMPLETYPE,
       
  2329         "basename": "NCName",
       
  2330         "extract": GenerateModelNameExtraction("NCName", NCName_model),
       
  2331         "facets": STRING_FACETS,
       
  2332         "generate": GenerateSimpleTypeXMLText(lambda x: x),
       
  2333         "initial": lambda: "",
       
  2334         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2335     },
       
  2336 
       
  2337     "anyURI": {
       
  2338         "type": SIMPLETYPE,
       
  2339         "basename": "anyURI",
       
  2340         "extract": GenerateModelNameExtraction("anyURI", URI_model),
       
  2341         "facets": STRING_FACETS,
       
  2342         "generate": GenerateSimpleTypeXMLText(lambda x: x),
       
  2343         "initial": lambda: "",
       
  2344         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2345     },
       
  2346 
       
  2347     "language": {
       
  2348         "type": SIMPLETYPE,
       
  2349         "basename": "language",
       
  2350         "extract": GenerateModelNameExtraction("language", LANGUAGE_model),
       
  2351         "facets": STRING_FACETS,
       
  2352         "generate": GenerateSimpleTypeXMLText(lambda x: x),
       
  2353         "initial": lambda: "en",
       
  2354         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2355     },
       
  2356 
       
  2357     "ID": {
       
  2358         "type": SIMPLETYPE,
       
  2359         "basename": "ID",
       
  2360         "extract": GenerateModelNameExtraction("ID", Name_model),
       
  2361         "facets": STRING_FACETS,
       
  2362         "generate": GenerateSimpleTypeXMLText(lambda x: x),
       
  2363         "initial": lambda: "",
       
  2364         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2365     },
       
  2366 
       
  2367     "IDREF": {
       
  2368         "type": SIMPLETYPE,
       
  2369         "basename": "IDREF",
       
  2370         "extract": GenerateModelNameExtraction("IDREF", Name_model),
       
  2371         "facets": STRING_FACETS,
       
  2372         "generate": GenerateSimpleTypeXMLText(lambda x: x),
       
  2373         "initial": lambda: "",
       
  2374         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2375     },
       
  2376 
       
  2377     "IDREFS": {
       
  2378         "type": SIMPLETYPE,
       
  2379         "basename": "IDREFS",
       
  2380         "extract": GenerateModelNameExtraction("IDREFS", Names_model),
       
  2381         "facets": STRING_FACETS,
       
  2382         "generate": GenerateSimpleTypeXMLText(lambda x: x),
       
  2383         "initial": lambda: "",
       
  2384         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2385     },
       
  2386 
       
  2387     "ENTITY": {
       
  2388         "type": SIMPLETYPE,
       
  2389         "basename": "ENTITY",
       
  2390         "extract": GenerateModelNameExtraction("ENTITY", Name_model),
       
  2391         "facets": STRING_FACETS,
       
  2392         "generate": GenerateSimpleTypeXMLText(lambda x: x),
       
  2393         "initial": lambda: "",
       
  2394         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2395     },
       
  2396 
       
  2397     "ENTITIES": {
       
  2398         "type": SIMPLETYPE,
       
  2399         "basename": "ENTITIES",
       
  2400         "extract": GenerateModelNameExtraction("ENTITIES", Names_model),
       
  2401         "facets": STRING_FACETS,
       
  2402         "generate": GenerateSimpleTypeXMLText(lambda x: x),
       
  2403         "initial": lambda: "",
       
  2404         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2405     },
       
  2406 
       
  2407     "NOTATION": {
       
  2408         "type": SIMPLETYPE,
       
  2409         "basename": "NOTATION",
       
  2410         "extract": GenerateModelNameExtraction("NOTATION", Name_model),
       
  2411         "facets": STRING_FACETS,
       
  2412         "generate": GenerateSimpleTypeXMLText(lambda x: x),
       
  2413         "initial": lambda: "",
       
  2414         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2415     },
       
  2416 
       
  2417     "NMTOKEN": {
       
  2418         "type": SIMPLETYPE,
       
  2419         "basename": "NMTOKEN",
       
  2420         "extract": GenerateModelNameExtraction("NMTOKEN", NMToken_model),
       
  2421         "facets": STRING_FACETS,
       
  2422         "generate": GenerateSimpleTypeXMLText(lambda x: x),
       
  2423         "initial": lambda: "",
       
  2424         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2425     },
       
  2426 
       
  2427     "NMTOKENS": {
       
  2428         "type": SIMPLETYPE,
       
  2429         "basename": "NMTOKENS",
       
  2430         "extract": GenerateModelNameExtraction("NMTOKENS", NMTokens_model),
       
  2431         "facets": STRING_FACETS,
       
  2432         "generate": GenerateSimpleTypeXMLText(lambda x: x),
       
  2433         "initial": lambda: "",
       
  2434         "check": lambda x: isinstance(x, (StringType, UnicodeType))
       
  2435     },
       
  2436 
       
  2437     # Complex Types
       
  2438     "anyType": {"type": COMPLEXTYPE, "extract": lambda x:None},
       
  2439 }
       
  2440 
       
  2441 if __name__ == '__main__':
       
  2442     classes = GenerateClassesFromXSD("test.xsd")
       
  2443     
       
  2444     # Code for test of test.xsd
       
  2445     xmlfile = open("po.xml", 'r')
       
  2446     tree = minidom.parse(xmlfile)
       
  2447     xmlfile.close()
       
  2448     test = classes["PurchaseOrderType"]()
       
  2449     for child in tree.childNodes:
       
  2450         if child.nodeType == tree.ELEMENT_NODE and child.nodeName == "purchaseOrder":
       
  2451             test.loadXMLTree(child)
       
  2452     test.items.item[0].setquantity(2)
       
  2453     testfile = open("test.xml", 'w')
       
  2454     testfile.write(u'<?xml version=\"1.0\"?>\n')
       
  2455     testfile.write(test.generateXMLText("purchaseOrder").encode("utf-8"))
       
  2456     testfile.close()