You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

2675 lines
90 KiB

  1. # Copyright (c) 2003, The Regents of the University of California,
  2. # through Lawrence Berkeley National Laboratory (subject to receipt of
  3. # any required approvals from the U.S. Dept. of Energy). All rights
  4. # reserved.
  5. #
  6. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
  7. #
  8. # This software is subject to the provisions of the Zope Public License,
  9. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
  10. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  11. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  12. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  13. # FOR A PARTICULAR PURPOSE.
  14. ident = "$Id$"
  15. import types, weakref, urllib, sys
  16. from threading import RLock
  17. from xml.dom.ext import SplitQName
  18. from xml.ns import SCHEMA, XMLNS
  19. from Utility import DOM, Collection
  20. from StringIO import StringIO
  21. class SchemaReader:
  22. """A SchemaReader creates XMLSchema objects from urls and xml data.
  23. """
  24. def __init__(self, domReader=None):
  25. """domReader -- class must implement DOMAdapterInterface
  26. """
  27. self.__readerClass = domReader
  28. if not self.__readerClass:
  29. self.__readerClass = DOMAdapter
  30. self._includes = {}
  31. self._imports = {}
  32. def __setImports(self, schema):
  33. """Add dictionary of imports to schema instance.
  34. schema -- XMLSchema instance
  35. """
  36. for ns,val in schema.imports.items():
  37. if self._imports.has_key(ns):
  38. schema.addImportSchema(self._imports[ns])
  39. def __setIncludes(self, schema):
  40. """Add dictionary of includes to schema instance.
  41. schema -- XMLSchema instance
  42. """
  43. for schemaLocation, val in schema.includes.items():
  44. if self._includes.has_key(schemaLocation):
  45. schema.addIncludeSchema(self._imports[schemaLocation])
  46. def addSchemaByLocation(self, location, schema):
  47. """provide reader with schema document for a location.
  48. """
  49. self._includes[location] = schema
  50. def addSchemaByNamespace(self, schema):
  51. """provide reader with schema document for a targetNamespace.
  52. """
  53. self._imports[schema.targetNamespace] = schema
  54. def loadFromNode(self, parent, element):
  55. """element -- DOM node or document
  56. parent -- WSDLAdapter instance
  57. """
  58. reader = self.__readerClass(element)
  59. schema = XMLSchema(parent)
  60. #HACK to keep a reference
  61. schema.wsdl = parent
  62. schema.load(reader)
  63. return schema
  64. def loadFromStream(self, file):
  65. """Return an XMLSchema instance loaded from a file object.
  66. file -- file object
  67. """
  68. reader = self.__readerClass()
  69. reader.loadDocument(file)
  70. schema = XMLSchema()
  71. schema.load(reader)
  72. self.__setIncludes(schema)
  73. self.__setImports(schema)
  74. return schema
  75. def loadFromString(self, data):
  76. """Return an XMLSchema instance loaded from an XML string.
  77. data -- XML string
  78. """
  79. return self.loadFromStream(StringIO(data))
  80. def loadFromURL(self, url):
  81. """Return an XMLSchema instance loaded from the given url.
  82. url -- URL to dereference
  83. """
  84. if not url.endswith('xsd'):
  85. raise SchemaError, 'unknown file type %s' %url
  86. reader = self.__readerClass()
  87. reader.loadFromURL(url)
  88. schema = XMLSchema()
  89. schema.load(reader)
  90. self.__setIncludes(schema)
  91. self.__setImports(schema)
  92. def loadFromFile(self, filename):
  93. """Return an XMLSchema instance loaded from the given file.
  94. filename -- name of file to open
  95. """
  96. file = open(filename, 'rb')
  97. try: schema = self.loadFromStream(file)
  98. finally: file.close()
  99. return schema
  100. class SchemaError(Exception):
  101. pass
  102. ###########################
  103. # DOM Utility Adapters
  104. ##########################
  105. class DOMAdapterInterface:
  106. def hasattr(self, attr):
  107. """return true if node has attribute
  108. attr - attribute to check for
  109. """
  110. raise NotImplementedError, 'adapter method not implemented'
  111. def getContentList(self, *contents):
  112. """returns an ordered list of child nodes
  113. *contents -- list of node names to return
  114. """
  115. raise NotImplementedError, 'adapter method not implemented'
  116. def setAttributeDictionary(self, attributes):
  117. """set attribute dictionary
  118. """
  119. raise NotImplementedError, 'adapter method not implemented'
  120. def getAttributeDictionary(self):
  121. """returns a dict of node's attributes
  122. """
  123. raise NotImplementedError, 'adapter method not implemented'
  124. def getTagName(self):
  125. """returns tagName of node
  126. """
  127. raise NotImplementedError, 'adapter method not implemented'
  128. def loadDocument(self, file):
  129. """load a Document from a file object
  130. file --
  131. """
  132. raise NotImplementedError, 'adapter method not implemented'
  133. def loadFromURL(self, url):
  134. """load a Document from an url
  135. url -- URL to dereference
  136. """
  137. raise NotImplementedError, 'adapter method not implemented'
  138. class DOMAdapter(DOMAdapterInterface):
  139. """Adapter for ZSI.Utility.DOM
  140. """
  141. def __init__(self, node=None):
  142. """Reset all instance variables.
  143. element -- DOM document, node, or None
  144. """
  145. if hasattr(node, 'documentElement'):
  146. self.__node = node.documentElement
  147. else:
  148. self.__node = node
  149. self.__attributes = None
  150. def hasattr(self, attr):
  151. """XXX assuming all xsd attributes not prefixed,
  152. all others are. Should ask xmlInterface so
  153. it can take care namespace mapping for
  154. prefixed attributes
  155. """
  156. if not self.__attributes:
  157. self.setAttributeDictionary()
  158. return self.__attributes.has_key(attr)
  159. def getContentList(self, *contents):
  160. nodes = []
  161. ELEMENT_NODE = self.__node.ELEMENT_NODE
  162. for child in DOM.getElements(self.__node, None):
  163. if child.nodeType == ELEMENT_NODE and\
  164. SplitQName(child.tagName)[1] in contents:
  165. nodes.append(child)
  166. return map(self.__class__, nodes)
  167. def setAttributeDictionary(self):
  168. self.__attributes = {}
  169. for v in self.__node._attrs.values():
  170. self.__attributes[v.nodeName] = v.nodeValue
  171. def getAttributeDictionary(self):
  172. if not self.__attributes:
  173. self.setAttributeDictionary()
  174. return self.__attributes
  175. def getTagName(self):
  176. return self.__node.tagName
  177. def loadDocument(self, file):
  178. self.__node = DOM.loadDocument(file)
  179. if hasattr(self.__node, 'documentElement'):
  180. self.__node = self.__node.documentElement
  181. def loadFromURL(self, url):
  182. self.__node = DOM.loadFromURL(url)
  183. if hasattr(self.__node, 'documentElement'):
  184. self.__node = self.__node.documentElement
  185. class XMLBase:
  186. """ These class variables are for string indentation.
  187. """
  188. __indent = 0
  189. __rlock = RLock()
  190. def __str__(self):
  191. XMLBase.__rlock.acquire()
  192. XMLBase.__indent += 1
  193. tmp = "<" + str(self.__class__) + '>\n'
  194. for k,v in self.__dict__.items():
  195. tmp += "%s* %s = %s\n" %(XMLBase.__indent*' ', k, v)
  196. XMLBase.__indent -= 1
  197. XMLBase.__rlock.release()
  198. return tmp
  199. ##########################################################
  200. # Schema Components
  201. #########################################################
  202. class XMLSchemaComponent(XMLBase):
  203. """
  204. class variables:
  205. required -- list of required attributes
  206. attributes -- dict of default attribute values, including None.
  207. Value can be a function for runtime dependencies.
  208. contents -- dict of namespace keyed content lists.
  209. 'xsd' content of xsd namespace.
  210. """
  211. required = []
  212. attributes = {}
  213. contents = {}
  214. xmlns_key = ''
  215. def __init__(self, parent=None):
  216. """parent -- parent instance
  217. instance variables:
  218. attributes -- dictionary of node's attributes
  219. """
  220. self.attributes = None
  221. self._parent = parent
  222. if self._parent:
  223. self._parent = weakref.ref(parent)
  224. if not self.__class__ == XMLSchemaComponent\
  225. and not (type(self.__class__.required) == type(XMLSchemaComponent.required)\
  226. and type(self.__class__.attributes) == type(XMLSchemaComponent.attributes)\
  227. and type(self.__class__.contents) == type(XMLSchemaComponent.contents)):
  228. raise RuntimeError, 'Bad type for a class variable in %s' %self.__class__
  229. def getTargetNamespace(self):
  230. """return targetNamespace
  231. """
  232. parent = self
  233. tns = self.attributes.get('targetNamespace')
  234. while not tns:
  235. parent = parent._parent()
  236. tns = parent.attributes.get('targetNamespace')
  237. return tns
  238. def getTypeDefinition(self, attribute):
  239. """attribute -- attribute with a QName value (eg. type).
  240. collection -- check types collection in parent Schema instance
  241. """
  242. return self.getQNameAttribute('types', attribute)
  243. def getElementDeclration(self, attribute):
  244. """attribute -- attribute with a QName value (eg. element).
  245. collection -- check elements collection in parent Schema instance.
  246. """
  247. return self.getQNameAttribute('elements', attribute)
  248. def getQNameAttribute(self, collection, attribute):
  249. """attribute -- an information item attribute, with a QName value.
  250. collection -- collection in parent Schema instance to search.
  251. """
  252. type_def = None
  253. tdc = self.attributes.get(attribute)
  254. if tdc:
  255. parent = self
  256. while not isinstance(parent, Schema):
  257. parent = parent._parent()
  258. if parent.targetNamespace == tdc.getTargetNamespace():
  259. type_def = getattr(parent, collection)[tdc.getName()]
  260. elif parent.imports.has_key(tdc.getTargetNamespace()):
  261. schema = parent.imports[tdc.getTargetNamespace()].getSchema()
  262. type_def = getattr(schema, collection)[tdc.getName()]
  263. else:
  264. raise SchemaError, 'missing import %s' %tdc
  265. return type_def
  266. def getXMLNS(self, prefix=None):
  267. """retrieve contents
  268. empty string returns 'xmlns'
  269. """
  270. parent = self
  271. ns = self.attributes['xmlns'].get(prefix)
  272. while not ns:
  273. parent = parent._parent()
  274. ns = parent.attributes['xmlns'].get(prefix or self.__class__.xmlns_key)
  275. return ns
  276. def getAttribute(self, attribute):
  277. """return requested attribute or None
  278. """
  279. return self.attributes.get(attribute)
  280. def setAttributes(self, node):
  281. """Sets up attribute dictionary, checks for required attributes and
  282. sets default attribute values. attr is for default attribute values
  283. determined at runtime.
  284. """
  285. self.attributes = {'xmlns':{}}
  286. for k,v in node.getAttributeDictionary().items():
  287. prefix,value = SplitQName(k)
  288. if value == 'xmlns':
  289. self.attributes[value][prefix or self.__class__.xmlns_key] = v
  290. elif prefix:
  291. ns = node.getNamespace(prefix)
  292. if ns == XMLNS or prefix == 'xml':
  293. self.attributes['xml'][k] = v
  294. elif ns in SCHEMA.XSD_LIST:
  295. self.attributes[value] = v
  296. else:
  297. raise SchemaError, 'attribute %s, namespace unknown' %k
  298. else:
  299. self.attributes[k] = v
  300. self.__checkAttributes()
  301. self.__setAttributeDefaults()
  302. #set QNames
  303. for k in ['type', 'element', 'base', 'ref', 'substitutionGroup', 'itemType']:
  304. if self.attributes.has_key(k):
  305. prefix, value = SplitQName(self.attributes.get(k))
  306. self.attributes[k] = \
  307. TypeDescriptionComponent((self.getXMLNS(prefix), value))
  308. #Union, memberTypes is a whitespace separated list of QNames
  309. if self.attributes.has_key('memberTypes'):
  310. qnames = self.attributes['memberTypes']
  311. def getContents(self, node):
  312. """retrieve xsd contents
  313. """
  314. return node.getContentList(*self.__class__.contents['xsd'])
  315. def __setAttributeDefaults(self):
  316. """Looks for default values for unset attributes. If
  317. class variable representing attribute is None, then
  318. it must be defined as a instance variable.
  319. """
  320. for k,v in self.attributes.items():
  321. if (not v) and (k != 'xmlns'):
  322. default_attr = getattr(self.__class__.attributes, k)
  323. if isinstance(default_attr, types.FunctionType):
  324. default_attr = default_attr()
  325. self.attributes[k] = default_attr
  326. def __checkAttributes(self):
  327. """Checks that required attributes have been defined,
  328. attributes w/default cannot be required. Checks
  329. all defined attributes are legal.
  330. """
  331. for a in self.__class__.required:
  332. if not self.attributes.has_key(a):
  333. raise SchemaError,\
  334. 'class instance %s, missing required attribute %s'\
  335. %(self.__class__, a)
  336. for a in self.attributes.keys():
  337. if a not in self.__class__.attributes.keys() + ['xmlns']:
  338. raise SchemaError, '%s, unknown attribute' %a
  339. class WSDLToolsAdapter(XMLSchemaComponent):
  340. """WSDL Adapter to grab the attributes from the wsdl document node.
  341. """
  342. attributes = {'name':None, 'targetNamespace':None}
  343. def __init__(self, wsdl):
  344. XMLSchemaComponent.__init__(self, None)
  345. self.setAttributes(DOMAdapter(wsdl.document))
  346. """Marker Interface: can determine something about an instances properties by using
  347. the provided convenience functions.
  348. """
  349. class DefinitionMarker:
  350. """marker for definitions
  351. """
  352. pass
  353. class DeclarationMarker:
  354. """marker for declarations
  355. """
  356. pass
  357. class AttributeMarker:
  358. """marker for attributes
  359. """
  360. pass
  361. class AttributeGroupMarker:
  362. """marker for attribute groups
  363. """
  364. pass
  365. class WildCardMarker:
  366. """marker for wildcards
  367. """
  368. pass
  369. class ElementMarker:
  370. """marker for wildcards
  371. """
  372. pass
  373. class ReferenceMarker:
  374. """marker for references
  375. """
  376. pass
  377. class ModelGroupMarker:
  378. """marker for model groups
  379. """
  380. pass
  381. class ExtensionMarker:
  382. """marker for extensions
  383. """
  384. pass
  385. class RestrictionMarker:
  386. """marker for restrictions
  387. """
  388. facets = ['enumeration', 'length', 'maxExclusive', 'maxInclusive',\
  389. 'maxLength', 'minExclusive', 'minInclusive', 'minLength',\
  390. 'pattern', 'fractionDigits', 'totalDigits', 'whiteSpace']
  391. class SimpleMarker:
  392. """marker for simple type information
  393. """
  394. pass
  395. class ComplexMarker:
  396. """marker for complex type information
  397. """
  398. pass
  399. class MarkerInterface:
  400. def isDefinition(self, what):
  401. return isinstance(what, DefinitionMarker)
  402. def isDeclaration(self, what):
  403. return isinstance(what, DeclarationMarker)
  404. def isAttribute(self, what):
  405. return isinstance(what, AttributeMarker)
  406. def isAttributeGroup(self, what):
  407. return isinstance(what, AttributeGroupMarker)
  408. def isReference(self, what):
  409. return isinstance(what, ReferenceMarker)
  410. def isWildCard(self, what):
  411. return isinstance(what, WildCardMarker)
  412. def isModelGroup(self, what):
  413. return isinstance(what, ModelGroupMarker)
  414. def isExtension(self, what):
  415. return isinstance(what, ModelGroupMarker)
  416. def isRestriction(self, what):
  417. return isinstance(what, ModelGroupMarker)
  418. def isSimple(self, what):
  419. return isinstance(what, SimpleMarker)
  420. def isComplex(self, what):
  421. return isinstance(what, ComplexMarker)
  422. class Notation(XMLSchemaComponent):
  423. """<notation>
  424. parent:
  425. schema
  426. attributes:
  427. id -- ID
  428. name -- NCName, Required
  429. public -- token, Required
  430. system -- anyURI
  431. contents:
  432. annotation?
  433. """
  434. required = ['name', 'public']
  435. attributes = {'id':None, 'name':None, 'public':None, 'system':None}
  436. contents = {'xsd':('annotation')}
  437. def __init__(self, parent):
  438. XMLSchemaComponent.__init__(self, parent)
  439. self.annotation = None
  440. def fromDom(self, node):
  441. self.setAttributes(node)
  442. contents = self.getContents(node)
  443. for i in contents:
  444. component = SplitQName(i.getTagName())[1]
  445. if component == 'annotation' and not self.annotation:
  446. self.annotation = Annotation(self)
  447. self.annotation.fromDom(i)
  448. else:
  449. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  450. class Annotation(XMLSchemaComponent):
  451. """<annotation>
  452. parent:
  453. all,any,anyAttribute,attribute,attributeGroup,choice,complexContent,
  454. complexType,element,extension,field,group,import,include,key,keyref,
  455. list,notation,redefine,restriction,schema,selector,simpleContent,
  456. simpleType,union,unique
  457. attributes:
  458. id -- ID
  459. contents:
  460. (documentation | appinfo)*
  461. """
  462. attributes = {'id':None}
  463. contents = {'xsd':('documentation', 'appinfo')}
  464. def __init__(self, parent):
  465. XMLSchemaComponent.__init__(self, parent)
  466. self.content = None
  467. def fromDom(self, node):
  468. self.setAttributes(node)
  469. contents = self.getContents(node)
  470. content = []
  471. for i in contents:
  472. component = SplitQName(i.getTagName())[1]
  473. if component == 'documentation':
  474. #print_debug('class %s, documentation skipped' %self.__class__, 5)
  475. continue
  476. elif component == 'appinfo':
  477. #print_debug('class %s, appinfo skipped' %self.__class__, 5)
  478. continue
  479. else:
  480. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  481. self.content = tuple(content)
  482. class Documentation(XMLSchemaComponent):
  483. """<documentation>
  484. parent:
  485. annotation
  486. attributes:
  487. source, anyURI
  488. xml:lang, language
  489. contents:
  490. mixed, any
  491. """
  492. attributes = {'source':None, 'xml:lang':None}
  493. contents = {'xsd':('mixed', 'any')}
  494. def __init__(self, parent):
  495. XMLSchemaComponent.__init__(self, parent)
  496. self.content = None
  497. def fromDom(self, node):
  498. self.setAttributes(node)
  499. contents = self.getContents(node)
  500. content = []
  501. for i in contents:
  502. component = SplitQName(i.getTagName())[1]
  503. if component == 'mixed':
  504. #print_debug('class %s, mixed skipped' %self.__class__, 5)
  505. continue
  506. elif component == 'any':
  507. #print_debug('class %s, any skipped' %self.__class__, 5)
  508. continue
  509. else:
  510. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  511. self.content = tuple(content)
  512. class Appinfo(XMLSchemaComponent):
  513. """<appinfo>
  514. parent:
  515. annotation
  516. attributes:
  517. source, anyURI
  518. contents:
  519. mixed, any
  520. """
  521. attributes = {'source':None, 'anyURI':None}
  522. contents = {'xsd':('mixed', 'any')}
  523. def __init__(self, parent):
  524. XMLSchemaComponent.__init__(self, parent)
  525. self.content = None
  526. def fromDom(self, node):
  527. self.setAttributes(node)
  528. contents = self.getContents(node)
  529. content = []
  530. for i in contents:
  531. component = SplitQName(i.getTagName())[1]
  532. if component == 'mixed':
  533. #print_debug('class %s, mixed skipped' %self.__class__, 5)
  534. continue
  535. elif component == 'any':
  536. #print_debug('class %s, any skipped' %self.__class__, 5)
  537. continue
  538. else:
  539. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  540. self.content = tuple(content)
  541. class XMLSchemaFake:
  542. # This is temporary, for the benefit of WSDL until the real thing works.
  543. def __init__(self, element):
  544. self.targetNamespace = DOM.getAttr(element, 'targetNamespace')
  545. self.element = element
  546. class XMLSchema(XMLSchemaComponent):
  547. """A schema is a collection of schema components derived from one
  548. or more schema documents, that is, one or more <schema> element
  549. information items. It represents the abstract notion of a schema
  550. rather than a single schema document (or other representation).
  551. <schema>
  552. parent:
  553. ROOT
  554. attributes:
  555. id -- ID
  556. version -- token
  557. xml:lang -- language
  558. targetNamespace -- anyURI
  559. attributeFormDefault -- 'qualified' | 'unqualified', 'unqualified'
  560. elementFormDefault -- 'qualified' | 'unqualified', 'unqualified'
  561. blockDefault -- '#all' | list of
  562. ('substitution | 'extension' | 'restriction')
  563. finalDefault -- '#all' | list of
  564. ('extension' | 'restriction' | 'list' | 'union')
  565. contents:
  566. ((include | import | redefine | annotation)*,
  567. (attribute, attributeGroup, complexType, element, group,
  568. notation, simpleType)*, annotation*)*
  569. attributes -- schema attributes
  570. imports -- import statements
  571. includes -- include statements
  572. redefines --
  573. types -- global simpleType, complexType definitions
  574. elements -- global element declarations
  575. attr_decl -- global attribute declarations
  576. attr_groups -- attribute Groups
  577. model_groups -- model Groups
  578. notations -- global notations
  579. """
  580. attributes = {'id':None,
  581. 'version':None,
  582. 'xml:lang':None,
  583. 'targetNamespace':None,
  584. 'attributeFormDefault':'unqualified',
  585. 'elementFormDefault':'unqualified',
  586. 'blockDefault':None,
  587. 'finalDefault':None}
  588. contents = {'xsd':('include', 'import', 'redefine', 'annotation', 'attribute',\
  589. 'attributeGroup', 'complexType', 'element', 'group',\
  590. 'notation', 'simpleType', 'annotation')}
  591. empty_namespace = ''
  592. def __init__(self, parent=None):
  593. """parent --
  594. instance variables:
  595. targetNamespace -- schema's declared targetNamespace, or empty string.
  596. _imported_schemas -- namespace keyed dict of schema dependencies, if
  597. a schema is provided instance will not resolve import statement.
  598. _included_schemas -- schemaLocation keyed dict of component schemas,
  599. if schema is provided instance will not resolve include statement.
  600. _base_url -- needed for relative URLs support, only works with URLs
  601. relative to initial document.
  602. includes -- collection of include statements
  603. imports -- collection of import statements
  604. elements -- collection of global element declarations
  605. types -- collection of global type definitions
  606. attr_decl -- collection of global attribute declarations
  607. attr_groups -- collection of global attribute group definitions
  608. model_groups -- collection of model group definitions
  609. notations -- collection of notations
  610. """
  611. self.targetNamespace = None
  612. XMLSchemaComponent.__init__(self, parent)
  613. self.includes = Collection(self)
  614. self.imports = Collection(self)
  615. self.elements = Collection(self)
  616. self.types = Collection(self)
  617. self.attr_decl = Collection(self)
  618. self.attr_groups = Collection(self)
  619. self.model_groups = Collection(self)
  620. self.notations = Collection(self)
  621. self._imported_schemas = {}
  622. self._included_schemas = {}
  623. self._base_url = None
  624. def addImportSchema(self, schema):
  625. """for resolving import statements in Schema instance
  626. schema -- schema instance
  627. _imported_schemas
  628. """
  629. if not isinstance(schema, Schema):
  630. raise TypeError, 'expecting a Schema instance'
  631. if schema.targetNamespace != self.targetNamespace:
  632. self._imported_schemas[schema.targetNamespace]
  633. else:
  634. raise SchemaError, 'import schema bad targetNamespace'
  635. def addIncludeSchema(self, schemaLocation, schema):
  636. """for resolving include statements in Schema instance
  637. schemaLocation -- schema location
  638. schema -- schema instance
  639. _included_schemas
  640. """
  641. if not isinstance(schema, Schema):
  642. raise TypeError, 'expecting a Schema instance'
  643. if not schema.targetNamespace or\
  644. schema.targetNamespace == self.targetNamespace:
  645. self._included_schemas[schemaLocation] = schema
  646. else:
  647. raise SchemaError, 'include schema bad targetNamespace'
  648. def setImportSchemas(self, schema_dict):
  649. """set the import schema dictionary, which is used to
  650. reference depedent schemas.
  651. """
  652. self._imported_schemas = schema_dict
  653. def getImportSchemas(self):
  654. """get the import schema dictionary, which is used to
  655. reference depedent schemas.
  656. """
  657. return self._imported_schemas
  658. def getSchemaNamespacesToImport(self):
  659. """returns tuple of namespaces the schema instance has declared
  660. itself to be depedent upon.
  661. """
  662. return tuple(self.includes.keys())
  663. def setIncludeSchemas(self, schema_dict):
  664. """set the include schema dictionary, which is keyed with
  665. schemaLocation (uri).
  666. This is a means of providing
  667. schemas to the current schema for content inclusion.
  668. """
  669. self._included_schemas = schema_dict
  670. def getIncludeSchemas(self):
  671. """get the include schema dictionary, which is keyed with
  672. schemaLocation (uri).
  673. """
  674. return self._included_schemas
  675. def getBaseUrl(self):
  676. """get base url, used for normalizing all relative uri's
  677. """
  678. return self._base_url
  679. def setBaseUrl(self, url):
  680. """set base url, used for normalizing all relative uri's
  681. """
  682. self._base_url = url
  683. def load(self, node):
  684. self.setAttributes(node)
  685. self.targetNamespace = self.getTargetNamespace()
  686. contents = self.getContents(node)
  687. indx = 0
  688. num = len(contents)
  689. while indx < num:
  690. while indx < num:
  691. node = contents[indx]
  692. component = SplitQName(node.getTagName())[1]
  693. if component == 'include':
  694. tp = self.__class__.Include(self)
  695. tp.fromDom(node)
  696. self.includes[tp.attributes['schemaLocation']] = tp
  697. schema = tp.getSchema()
  698. if schema.targetNamespace and \
  699. schema.targetNamespace != self.targetNamespace:
  700. raise SchemaError, 'included schema bad targetNamespace'
  701. for collection in ['imports','elements','types',\
  702. 'attr_decl','attr_groups','model_groups','notations']:
  703. for k,v in getattr(schema,collection).items():
  704. if not getattr(self,collection).has_key(k):
  705. setattr(self,collection,v)
  706. elif component == 'import':
  707. tp = self.__class__.Import(self)
  708. tp.fromDom(node)
  709. if tp.attributes['namespace']:
  710. if tp.attributes['namespace'] == self.targetNamespace:
  711. raise SchemaError,\
  712. 'import and schema have same targetNamespace'
  713. self.imports[tp.attributes['namespace']] = tp
  714. else:
  715. self.imports[self.__class__.empty_namespace] = tp
  716. elif component == 'redefine':
  717. #print_debug('class %s, redefine skipped' %self.__class__, 5)
  718. pass
  719. elif component == 'annotation':
  720. #print_debug('class %s, annotation skipped' %self.__class__, 5)
  721. pass
  722. else:
  723. break
  724. indx += 1
  725. while indx < num:
  726. node = contents[indx]
  727. component = SplitQName(node.getTagName())[1]
  728. if component == 'complexType':
  729. tp = ComplexType(self)
  730. tp.fromDom(node)
  731. self.types[tp.getAttribute('name')] = tp
  732. elif component == 'element':
  733. tp = ElementDeclaration(self)
  734. tp.fromDom(node)
  735. self.elements[tp.getAttribute('name')] = tp
  736. elif component == 'simpleType':
  737. tp = SimpleType(self)
  738. tp.fromDom(node)
  739. self.types[tp.getAttribute('name')] = tp
  740. elif component == 'group':
  741. tp = ModelGroupDefinition(self)
  742. tp.fromDom(node)
  743. self.modelGroups[tp.getAttribute('name')] = tp
  744. elif component == 'notation':
  745. tp = Notation(self)
  746. tp.fromDom(node)
  747. self.notations[tp.getAttribute('name')] = tp
  748. else:
  749. break
  750. indx += 1
  751. while indx < num:
  752. node = contents[indx]
  753. component = SplitQName(node.getTagName())[1]
  754. if component == 'annotation':
  755. #print_debug('class %s, annotation 2 skipped' %self.__class__, 5)
  756. pass
  757. else:
  758. break
  759. indx += 1
  760. class Import(XMLSchemaComponent):
  761. """<import>
  762. parent:
  763. schema
  764. attributes:
  765. id -- ID
  766. namespace -- anyURI
  767. schemaLocation -- anyURI
  768. contents:
  769. annotation?
  770. """
  771. attributes = {'id':None,
  772. 'namespace':None,
  773. 'schemaLocation':None}
  774. contents = {'xsd':['annotation']}
  775. def __init__(self, parent):
  776. XMLSchemaComponent.__init__(self, parent)
  777. self.annotation = None
  778. def fromDom(self, node):
  779. self.setAttributes(node)
  780. contents = self.getContents(node)
  781. if self.attributes['namespace'] == self._parent().attributes['targetNamespace']:
  782. raise SchemaError, 'namespace (%s) of schema and import match'
  783. for i in contents:
  784. component = SplitQName(i.getTagName())[1]
  785. if component == 'annotation' and not self.annotation:
  786. self.annotation = Annotation(self)
  787. self.annotation.fromDom(i)
  788. else:
  789. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  790. def getSchema(self):
  791. """if schema is not defined, first look for a Schema class instance
  792. in parent Schema. Else if not defined resolve schemaLocation
  793. and create a new Schema class instance.
  794. """
  795. if not self._schema:
  796. schema = self._parent()._parent()
  797. self._schema = schema.getImportSchemas()[self.attributes['namespace']]
  798. if not self._schema:
  799. url = urllib.basejoin(schema.getBaseUrl(),\
  800. self.attributes['schemaLocation'])
  801. reader = SchemaReader()
  802. reader._imports = schema.getImportSchemas()
  803. reader._includes = schema.getIncludeSchemas()
  804. self._schema = reader.readFromUrl(url)
  805. self._schema.setBaseUrl(url)
  806. return self._schema
  807. class Include(XMLSchemaComponent):
  808. """<include schemaLocation>
  809. parent:
  810. schema
  811. attributes:
  812. id -- ID
  813. schemaLocation -- anyURI, required
  814. contents:
  815. annotation?
  816. """
  817. required = ['schemaLocation']
  818. attributes = {'id':None,
  819. 'schemaLocation':None}
  820. contents = {'xsd':['annotation']}
  821. def __init__(self, parent):
  822. XMLSchemaComponent.__init__(self, parent)
  823. self.annotation = None
  824. self._schema = None
  825. def fromDom(self, node):
  826. self.setAttributes(node)
  827. contents = self.getContents(node)
  828. for i in contents:
  829. component = SplitQName(i.getTagName())[1]
  830. if component == 'annotation' and not self.annotation:
  831. self.annotation = Annotation(self)
  832. self.annotation.fromDom(i)
  833. else:
  834. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  835. def getSchema(self):
  836. """if schema is not defined, first look for a Schema class instance
  837. in parent Schema. Else if not defined resolve schemaLocation
  838. and create a new Schema class instance.
  839. """
  840. if not self._schema:
  841. schema = self._parent()._parent()
  842. self._schema = schema.getIncludeSchemas(\
  843. self.attributes['schemaLocation'])
  844. if not self._schema:
  845. url = BaseUriResolver().normalize(\
  846. self.attributes['schemaLocation'], schema.getBaseUrl())
  847. reader = SchemaReader()
  848. reader._imports = schema.getImportSchemas()
  849. reader._includes = schema.getIncludeSchemas()
  850. self._schema = reader.readFromUrl(url)
  851. self._schema.setBaseUrl(url)
  852. return self._schema
  853. class AttributeDeclaration(XMLSchemaComponent,\
  854. MarkerInterface,\
  855. AttributeMarker,\
  856. DeclarationMarker):
  857. """<attribute name>
  858. parent:
  859. schema
  860. attributes:
  861. id -- ID
  862. name -- NCName, required
  863. type -- QName
  864. default -- string
  865. fixed -- string
  866. contents:
  867. annotation?, simpleType?
  868. """
  869. required = ['name']
  870. attributes = {'id':None,
  871. 'name':None,
  872. 'type':None,
  873. 'default':None,
  874. 'fixed':None}
  875. contents = {'xsd':['annotation','simpleType']}
  876. def __init__(self, parent):
  877. XMLSchemaComponent.__init__(self, parent)
  878. self.annotation = None
  879. self.content = None
  880. def fromDom(self, node):
  881. """ No list or union support
  882. """
  883. self.setAttributes(node)
  884. contents = self.getContents(node)
  885. for i in contents:
  886. component = SplitQName(i.getTagName())[1]
  887. if component == 'annotation' and not self.annotation:
  888. self.annotation = Annotation(self)
  889. self.annotation.fromDom(i)
  890. elif component == 'simpleType':
  891. self.content = SimpleType(self)
  892. self.content.fromDom(i)
  893. else:
  894. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  895. class LocalAttributeDeclaration(AttributeDeclaration,\
  896. MarkerInterface,\
  897. AttributeMarker,\
  898. DeclarationMarker):
  899. """<attribute name>
  900. parent:
  901. complexType, restriction, extension, attributeGroup
  902. attributes:
  903. id -- ID
  904. name -- NCName, required
  905. type -- QName
  906. form -- ('qualified' | 'unqualified'), schema.attributeFormDefault
  907. use -- ('optional' | 'prohibited' | 'required'), optional
  908. default -- string
  909. fixed -- string
  910. contents:
  911. annotation?, simpleType?
  912. """
  913. required = ['name']
  914. attributes = {'id':None,
  915. 'name':None,
  916. 'type':None,
  917. 'form':lambda: self._parent.parent().getAttributeFormDefault(),
  918. 'use':'optional',
  919. 'default':None,
  920. 'fixed':None}
  921. contents = {'xsd':['annotation','simpleType']}
  922. def __init__(self, parent):
  923. AttributeDeclaration.__init__(self, parent)
  924. self.annotation = None
  925. self.content = None
  926. def fromDom(self, node):
  927. self.setAttributes(node)
  928. contents = self.getContents(node)
  929. for i in contents:
  930. component = SplitQName(i.getTagName())[1]
  931. if component == 'annotation' and not self.annotation:
  932. self.annotation = Annotation(self)
  933. self.annotation.fromDom(i)
  934. elif component == 'simpleType':
  935. self.content = SimpleType(self)
  936. self.content.fromDom(i)
  937. else:
  938. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  939. class AttributeWildCard(XMLSchemaComponent,\
  940. MarkerInterface,\
  941. AttributeMarker,\
  942. DeclarationMarker,\
  943. WildCardMarker):
  944. """<anyAttribute>
  945. parents:
  946. complexType, restriction, extension, attributeGroup
  947. attributes:
  948. id -- ID
  949. namespace -- '##any' | '##other' |
  950. (anyURI* | '##targetNamespace' | '##local'), ##any
  951. processContents -- 'lax' | 'skip' | 'strict', strict
  952. contents:
  953. annotation?
  954. """
  955. attributes = {'id':None,
  956. 'namespace':'##any',
  957. 'processContents':'strict'}
  958. contents = {'xsd':['annotation']}
  959. def __init__(self, parent):
  960. XMLSchemaComponent.__init__(self, parent)
  961. self.annotation = None
  962. def fromDom(self, node):
  963. self.setAttributes(node)
  964. contents = self.getContents(node)
  965. for i in contents:
  966. component = SplitQName(i.getTagName())[1]
  967. if component == 'annotation' and not self.annotation:
  968. self.annotation = Annotation(self)
  969. self.annotation.fromDom(i)
  970. else:
  971. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  972. class AttributeReference(XMLSchemaComponent,\
  973. MarkerInterface,\
  974. AttributeMarker,\
  975. ReferenceMarker):
  976. """<attribute ref>
  977. parents:
  978. complexType, restriction, extension, attributeGroup
  979. attributes:
  980. id -- ID
  981. ref -- QName, required
  982. use -- ('optional' | 'prohibited' | 'required'), optional
  983. default -- string
  984. fixed -- string
  985. contents:
  986. annotation?
  987. """
  988. required = ['ref']
  989. attributes = {'id':None,
  990. 'ref':None,
  991. 'use':'optional',
  992. 'default':None,
  993. 'fixed':None}
  994. contents = {'xsd':['annotation']}
  995. def __init__(self, parent):
  996. XMLSchemaComponent.__init__(self, parent)
  997. self.annotation = None
  998. def fromDom(self, node):
  999. self.setAttributes(node)
  1000. contents = self.getContents(node)
  1001. for i in contents:
  1002. component = SplitQName(i.getTagName())[1]
  1003. if component == 'annotation' and not self.annotation:
  1004. self.annotation = Annotation(self)
  1005. self.annotation.fromDom(i)
  1006. else:
  1007. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1008. class AttributeGroupDefinition(XMLSchemaComponent,\
  1009. MarkerInterface,\
  1010. AttributeGroupMarker,\
  1011. DefinitionMarker):
  1012. """<attributeGroup name>
  1013. parents:
  1014. schema, redefine
  1015. attributes:
  1016. id -- ID
  1017. name -- NCName, required
  1018. contents:
  1019. annotation?
  1020. """
  1021. required = ['name']
  1022. attributes = {'id':None,
  1023. 'name':None}
  1024. contents = {'xsd':['annotation']}
  1025. def __init__(self, parent):
  1026. XMLSchemaComponent.__init__(self, parent)
  1027. self.annotation = None
  1028. def fromDom(self, node):
  1029. self.setAttributes(node)
  1030. contents = self.getContents(node)
  1031. for i in contents:
  1032. component = SplitQName(i.getTagName())[1]
  1033. if component == 'annotation' and not self.annotation:
  1034. self.annotation = Annotation(self)
  1035. self.annotation.fromDom(i)
  1036. else:
  1037. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1038. class AttributeGroupReference(XMLSchemaComponent,\
  1039. MarkerInterface,\
  1040. AttributeGroupMarker,\
  1041. ReferenceMarker):
  1042. """<attributeGroup ref>
  1043. parents:
  1044. complexType, restriction, extension, attributeGroup
  1045. attributes:
  1046. id -- ID
  1047. ref -- QName, required
  1048. contents:
  1049. annotation?
  1050. """
  1051. required = ['ref']
  1052. attributes = {'id':None,
  1053. 'ref':None}
  1054. contents = {'xsd':['annotation']}
  1055. def __init__(self, parent):
  1056. XMLSchemaComponent.__init__(self, parent)
  1057. self.annotation = None
  1058. def fromDom(self, node):
  1059. self.setAttributes(node)
  1060. contents = self.getContents(node)
  1061. for i in contents:
  1062. component = SplitQName(i.getTagName())[1]
  1063. if component == 'annotation' and not self.annotation:
  1064. self.annotation = Annotation(self)
  1065. self.annotation.fromDom(i)
  1066. else:
  1067. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1068. ######################################################
  1069. # Elements
  1070. #####################################################
  1071. class IdentityConstrants(XMLSchemaComponent):
  1072. """Allow one to uniquely identify nodes in a document and ensure the
  1073. integrity of references between them.
  1074. attributes -- dictionary of attributes
  1075. selector -- XPath to selected nodes
  1076. fields -- list of XPath to key field
  1077. """
  1078. def __init__(self, parent):
  1079. XMLSchemaComponent.__init__(self, parent)
  1080. self.selector = None
  1081. self.fields = None
  1082. self.annotation = None
  1083. def fromDom(node):
  1084. self.setAttributes(node)
  1085. contents = self.getContents(node)
  1086. fields = []
  1087. for i in contents:
  1088. component = SplitQName(i.getTagName())[1]
  1089. if component in self.__class__.contents['xsd']:
  1090. if component == 'annotation' and not self.annotation:
  1091. self.annotation = Annotation(self)
  1092. self.annotation.fromDom(i)
  1093. elif component == 'selector':
  1094. self.selector = self.Selector(self)
  1095. self.selector.fromDom(i)
  1096. continue
  1097. elif component == 'field':
  1098. fields.append(self.Field(self))
  1099. fields[-1].fromDom(i)
  1100. continue
  1101. else:
  1102. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1103. else:
  1104. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1105. self.fields = tuple(fields)
  1106. class Constraint(XMLSchemaComponent):
  1107. def __init__(self, parent):
  1108. XMLSchemaComponent.__init__(self, parent)
  1109. self.annotation = None
  1110. def fromDom(node):
  1111. self.setAttributes(node)
  1112. contents = self.getContents(node)
  1113. for i in contents:
  1114. component = SplitQName(i.getTagName())[1]
  1115. if component in self.__class__.contents['xsd']:
  1116. if component == 'annotation' and not self.annotation:
  1117. self.annotation = Annotation(self)
  1118. self.annotation.fromDom(i)
  1119. else:
  1120. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1121. else:
  1122. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1123. class Selector(Constraint):
  1124. """<selector xpath>
  1125. parent:
  1126. unique, key, keyref
  1127. attributes:
  1128. id -- ID
  1129. xpath -- XPath subset, required
  1130. contents:
  1131. annotation?
  1132. """
  1133. required = ['xpath']
  1134. attributes = {'id':None,
  1135. 'xpath':None}
  1136. contents = {'xsd':['annotation']}
  1137. class Field(Constraint):
  1138. """<field xpath>
  1139. parent:
  1140. unique, key, keyref
  1141. attributes:
  1142. id -- ID
  1143. xpath -- XPath subset, required
  1144. contents:
  1145. annotation?
  1146. """
  1147. required = ['xpath']
  1148. attributes = {'id':None,
  1149. 'xpath':None}
  1150. contents = {'xsd':['annotation']}
  1151. class Unique(IdentityConstrants):
  1152. """<unique name> Enforce fields are unique w/i a specified scope.
  1153. parent:
  1154. element
  1155. attributes:
  1156. id -- ID
  1157. name -- NCName, required
  1158. contents:
  1159. annotation?, selector, field+
  1160. """
  1161. required = ['name']
  1162. attributes = {'id':None,
  1163. 'name':None}
  1164. contents = {'xsd':['annotation', 'selector', 'field']}
  1165. class Key(IdentityConstrants):
  1166. """<key name> Enforce fields are unique w/i a specified scope, and all
  1167. field values are present w/i document. Fields cannot
  1168. be nillable.
  1169. parent:
  1170. element
  1171. attributes:
  1172. id -- ID
  1173. name -- NCName, required
  1174. contents:
  1175. annotation?, selector, field+
  1176. """
  1177. required = ['name']
  1178. attributes = {'id':None,
  1179. 'name':None}
  1180. contents = {'xsd':['annotation', 'selector', 'field']}
  1181. class KeyRef(IdentityConstrants):
  1182. """<keyref name refer> Ensure a match between two sets of values in an
  1183. instance.
  1184. parent:
  1185. element
  1186. attributes:
  1187. id -- ID
  1188. name -- NCName, required
  1189. refer -- QName, required
  1190. contents:
  1191. annotation?, selector, field+
  1192. """
  1193. required = ['name', 'refer']
  1194. attributes = {'id':None,
  1195. 'name':None,
  1196. 'refer':None}
  1197. contents = {'xsd':['annotation', 'selector', 'field']}
  1198. class ElementDeclaration(XMLSchemaComponent,\
  1199. MarkerInterface,\
  1200. ElementMarker,\
  1201. DeclarationMarker):
  1202. """<element name>
  1203. parents:
  1204. schema
  1205. attributes:
  1206. id -- ID
  1207. name -- NCName, required
  1208. type -- QName
  1209. default -- string
  1210. fixed -- string
  1211. nillable -- boolean, false
  1212. abstract -- boolean, false
  1213. substitutionGroup -- QName
  1214. block -- ('#all' | ('substition' | 'extension' | 'restriction')*),
  1215. schema.blockDefault
  1216. final -- ('#all' | ('extension' | 'restriction')*),
  1217. schema.finalDefault
  1218. contents:
  1219. annotation?, (simpleType,complexType)?, (key | keyref | unique)*
  1220. """
  1221. required = ['name']
  1222. attributes = {'id':None,
  1223. 'name':None,
  1224. 'type':None,
  1225. 'default':None,
  1226. 'fixed':None,
  1227. 'nillable':0,
  1228. 'abstract':0,
  1229. 'block':lambda: self.parent.parent().getBlockDefault(),
  1230. 'final':lambda: self.parent.parent().getFinalDefault()}
  1231. contents = {'xsd':['annotation', 'simpleType', 'complexType', 'key',\
  1232. 'keyref', 'unique']}
  1233. def __init__(self, parent):
  1234. XMLSchemaComponent.__init__(self, parent)
  1235. self.annotation = None
  1236. self.content = None
  1237. self.constraints = None
  1238. def fromDom(self, node):
  1239. self.setAttributes(node)
  1240. contents = self.getContents(node)
  1241. constraints = []
  1242. for i in contents:
  1243. component = SplitQName(i.getTagName())[1]
  1244. if component in self.__class__.contents['xsd']:
  1245. if component == 'annotation' and not self.annotation:
  1246. self.annotation = Annotation(self)
  1247. self.annotation.fromDom(i)
  1248. elif component == 'simpleType' and not self.content:
  1249. self.content = AnonymousSimpleType(self)
  1250. self.content.fromDom(i)
  1251. elif component == 'complexType' and not self.content:
  1252. self.content = LocalComplexType(self)
  1253. self.content.fromDom(i)
  1254. elif component == 'key':
  1255. constraints.append(Key(self))
  1256. constraints[-1].fromDom(i)
  1257. elif component == 'keyref':
  1258. constraints.append(KeyRef(self))
  1259. constraints[-1].fromDom(i)
  1260. elif component == 'unique':
  1261. constraints.append(Unique(self))
  1262. constraints[-1].fromDom(i)
  1263. else:
  1264. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1265. else:
  1266. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1267. self.constraints = tuple(constraints)
  1268. class LocalElementDeclaration(ElementDeclaration,\
  1269. MarkerInterface,\
  1270. ElementMarker,\
  1271. DeclarationMarker):
  1272. """<element>
  1273. parents:
  1274. all, choice, sequence
  1275. attributes:
  1276. id -- ID
  1277. name -- NCName, required
  1278. form -- ('qualified' | 'unqualified'), schema.elementFormDefault
  1279. type -- QName
  1280. minOccurs -- Whole Number, 1
  1281. maxOccurs -- (Whole Number | 'unbounded'), 1
  1282. default -- string
  1283. fixed -- string
  1284. nillable -- boolean, false
  1285. block -- ('#all' | ('extension' | 'restriction')*), schema.blockDefault
  1286. contents:
  1287. annotation?, (simpleType,complexType)?, (key | keyref | unique)*
  1288. """
  1289. required = ['name']
  1290. attributes = {'id':None,
  1291. 'name':None,
  1292. 'form':lambda: self._parent.parent().getElementFormDefault(),
  1293. 'type':None,
  1294. 'minOccurs':'1',
  1295. 'maxOccurs':'1',
  1296. 'default':None,
  1297. 'fixed':None,
  1298. 'nillable':0,
  1299. 'abstract':0,
  1300. 'block':lambda: self.parent.parent().getBlockDefault()}
  1301. contents = {'xsd':['annotation', 'simpleType', 'complexType', 'key',\
  1302. 'keyref', 'unique']}
  1303. class ElementReference(ElementDeclaration,\
  1304. MarkerInterface,\
  1305. ElementMarker,\
  1306. ReferenceMarker):
  1307. """<element ref>
  1308. parents:
  1309. all, choice, sequence
  1310. attributes:
  1311. id -- ID
  1312. ref -- QName, required
  1313. minOccurs -- Whole Number, 1
  1314. maxOccurs -- (Whole Number | 'unbounded'), 1
  1315. contents:
  1316. annotation?
  1317. """
  1318. required = ['ref']
  1319. attributes = {'id':None,
  1320. 'ref':None,
  1321. 'minOccurs':'1',
  1322. 'maxOccurs':'1'}
  1323. contents = {'xsd':['annotation']}
  1324. class ElementWildCard(LocalElementDeclaration,\
  1325. MarkerInterface,\
  1326. ElementMarker,\
  1327. DeclarationMarker,\
  1328. WildCardMarker):
  1329. """<any>
  1330. parents:
  1331. choice, sequence
  1332. attributes:
  1333. id -- ID
  1334. minOccurs -- Whole Number, 1
  1335. maxOccurs -- (Whole Number | 'unbounded'), 1
  1336. namespace -- '##any' | '##other' |
  1337. (anyURI* | '##targetNamespace' | '##local'), ##any
  1338. processContents -- 'lax' | 'skip' | 'strict', strict
  1339. contents:
  1340. annotation?
  1341. """
  1342. required = []
  1343. attributes = {'id':None,
  1344. 'minOccurs':'1',
  1345. 'maxOccurs':'1',
  1346. 'namespace':'##any',
  1347. 'processContents':'strict'}
  1348. contents = {'xsd':['annotation']}
  1349. ######################################################
  1350. # Model Groups
  1351. #####################################################
  1352. class Sequence(XMLSchemaComponent,\
  1353. MarkerInterface,\
  1354. ModelGroupMarker):
  1355. """<sequence>
  1356. parents:
  1357. complexType, extension, restriction, group, choice, sequence
  1358. attributes:
  1359. id -- ID
  1360. minOccurs -- Whole Number, 1
  1361. maxOccurs -- (Whole Number | 'unbounded'), 1
  1362. contents:
  1363. annotation?, (element | group | choice | sequence | any)*
  1364. """
  1365. attributes = {'id':None,
  1366. 'minOccurs':'1',
  1367. 'maxOccurs':'1'}
  1368. contents = {'xsd':['annotation', 'element', 'group', 'choice', 'sequence',\
  1369. 'any']}
  1370. def __init__(self, parent):
  1371. XMLSchemaComponent.__init__(self, parent)
  1372. self.annotation = None
  1373. self.content = None
  1374. def fromDom(self, node):
  1375. self.setAttributes(node)
  1376. contents = self.getContents(node)
  1377. content = []
  1378. for i in contents:
  1379. component = SplitQName(i.getTagName())[1]
  1380. if component in self.__class__.contents['xsd']:
  1381. if component == 'annotation' and not self.annotation:
  1382. self.annotation = Annotation(self)
  1383. self.annotation.fromDom(i)
  1384. continue
  1385. elif component == 'element':
  1386. if i.hasattr('ref'):
  1387. content.append(ElementReference(self))
  1388. else:
  1389. content.append(LocalElementDeclaration(self))
  1390. elif component == 'group':
  1391. content.append(ModelGroupReference(self))
  1392. elif component == 'choice':
  1393. content.append(Choice(self))
  1394. elif component == 'sequence':
  1395. content.append(Sequence(self))
  1396. elif component == 'any':
  1397. content.append(ElementWildCard(self))
  1398. else:
  1399. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1400. content[-1].fromDom(i)
  1401. else:
  1402. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1403. self.content = tuple(content)
  1404. class All(XMLSchemaComponent,\
  1405. MarkerInterface,\
  1406. ModelGroupMarker):
  1407. """<all>
  1408. parents:
  1409. complexType, extension, restriction, group
  1410. attributes:
  1411. id -- ID
  1412. minOccurs -- '0' | '1', 1
  1413. maxOccurs -- '1', 1
  1414. contents:
  1415. annotation?, element*
  1416. """
  1417. attributes = {'id':None,
  1418. 'minOccurs':'1',
  1419. 'maxOccurs':'1'}
  1420. contents = {'xsd':['annotation', 'element']}
  1421. def __init__(self, parent):
  1422. XMLSchemaComponent.__init__(self, parent)
  1423. self.annotation = None
  1424. self.content = None
  1425. def fromDom(self, node):
  1426. self.setAttributes(node)
  1427. contents = self.getContents(node)
  1428. content = []
  1429. for i in contents:
  1430. component = SplitQName(i.getTagName())[1]
  1431. if component in self.__class__.contents['xsd']:
  1432. if component == 'annotation' and not self.annotation:
  1433. self.annotation = Annotation(self)
  1434. self.annotation.fromDom(i)
  1435. continue
  1436. elif component == 'element':
  1437. if i.hasattr('ref'):
  1438. content.append(ElementReference(self))
  1439. else:
  1440. content.append(LocalElementDeclaration(self))
  1441. else:
  1442. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1443. content[-1].fromDom(i)
  1444. else:
  1445. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1446. self.content = tuple(content)
  1447. class Choice(XMLSchemaComponent,\
  1448. MarkerInterface,\
  1449. ModelGroupMarker):
  1450. """<choice>
  1451. parents:
  1452. complexType, extension, restriction, group, choice, sequence
  1453. attributes:
  1454. id -- ID
  1455. minOccurs -- Whole Number, 1
  1456. maxOccurs -- (Whole Number | 'unbounded'), 1
  1457. contents:
  1458. annotation?, (element | group | choice | sequence | any)*
  1459. """
  1460. attributes = {'id':None,
  1461. 'minOccurs':'1',
  1462. 'maxOccurs':'1'}
  1463. contents = {'xsd':['annotation', 'element', 'group', 'choice', 'sequence',\
  1464. 'any']}
  1465. def __init__(self, parent):
  1466. XMLSchemaComponent.__init__(self, parent)
  1467. self.annotation = None
  1468. self.content = None
  1469. def fromDom(self, node):
  1470. self.setAttributes(node)
  1471. contents = self.getContents(node)
  1472. content = []
  1473. for i in contents:
  1474. component = SplitQName(i.getTagName())[1]
  1475. if component in self.__class__.contents['xsd']:
  1476. if component == 'annotation' and not self.annotation:
  1477. self.annotation = Annotation(self)
  1478. self.annotation.fromDom(i)
  1479. continue
  1480. elif component == 'element':
  1481. if i.hasattr('ref'):
  1482. content.append(ElementReference(self))
  1483. else:
  1484. content.append(LocalElementDeclaration(self))
  1485. elif component == 'group':
  1486. content.append(ModelGroupReference(self))
  1487. elif component == 'choice':
  1488. content.append(Choice(self))
  1489. elif component == 'sequence':
  1490. content.append(Sequence(self))
  1491. elif component == 'any':
  1492. content.append(ElementWildCard(self))
  1493. else:
  1494. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1495. content[-1].fromDom(i)
  1496. else:
  1497. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1498. self.content = tuple(content)
  1499. class ModelGroupDefinition(XMLSchemaComponent,\
  1500. MarkerInterface,\
  1501. ModelGroupMarker,\
  1502. DefinitionMarker):
  1503. """<group name>
  1504. parents:
  1505. redefine, schema
  1506. attributes:
  1507. id -- ID
  1508. name -- NCName, required
  1509. contents:
  1510. annotation?, (all | choice | sequence)?
  1511. """
  1512. required = ['name']
  1513. attributes = {'id':None,
  1514. 'name':None}
  1515. contents = {'xsd':['annotation', 'all', 'choice', 'sequence']}
  1516. def __init__(self, parent):
  1517. XMLSchemaComponent.__init__(self, parent)
  1518. self.annotation = None
  1519. self.content = None
  1520. def fromDom(self, node):
  1521. self.setAttributes(node)
  1522. contents = self.getContents(node)
  1523. for i in contents:
  1524. component = SplitQName(i.getTagName())[1]
  1525. if component in self.__class__.contents['xsd']:
  1526. if component == 'annotation' and not self.annotation:
  1527. self.annotation = Annotation()
  1528. self.annotation.fromDom(i)
  1529. continue
  1530. elif component == 'all' and not self.content:
  1531. self.content = All(self)
  1532. elif component == 'choice' and not self.content:
  1533. self.content = Choice(self)
  1534. elif component == 'sequence' and not self.content:
  1535. self.content = Sequence(self)
  1536. else:
  1537. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1538. self.content.fromDom(i)
  1539. else:
  1540. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1541. class ModelGroupReference(XMLSchemaComponent,\
  1542. MarkerInterface,\
  1543. ModelGroupMarker,\
  1544. ReferenceMarker):
  1545. """<group ref>
  1546. parents:
  1547. choice, complexType, extension, restriction, sequence
  1548. attributes:
  1549. id -- ID
  1550. ref -- NCName, required
  1551. contents:
  1552. annotation?
  1553. """
  1554. required = ['ref']
  1555. attributes = {'id':None,
  1556. 'ref':None}
  1557. contents = {'xsd':['annotation']}
  1558. def __init__(self, parent):
  1559. XMLSchemaComponent.__init__(self, parent)
  1560. self.annotation = None
  1561. def fromDom(self, node):
  1562. self.setAttributes(node)
  1563. contents = self.getContents(node)
  1564. for i in contents:
  1565. component = SplitQName(i.getTagName())[1]
  1566. if component in self.__class__.contents['xsd']:
  1567. if component == 'annotation' and not self.annotation:
  1568. self.annotation = Annotation(self)
  1569. self.annotation.fromDom(i)
  1570. else:
  1571. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1572. else:
  1573. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1574. class ComplexType(XMLSchemaComponent,\
  1575. MarkerInterface,\
  1576. DefinitionMarker,\
  1577. ComplexMarker):
  1578. """<complexType name>
  1579. parents:
  1580. redefine, schema
  1581. attributes:
  1582. id -- ID
  1583. name -- NCName, required
  1584. mixed -- boolean, false
  1585. abstract -- boolean, false
  1586. block -- ('#all' | ('extension' | 'restriction')*), schema.blockDefault
  1587. final -- ('#all' | ('extension' | 'restriction')*), schema.finalDefault
  1588. contents:
  1589. annotation?, (simpleContent | complexContent |
  1590. ((group | all | choice | sequence)?, (attribute | attributeGroup)*, anyAttribute?))
  1591. """
  1592. required = ['name']
  1593. attributes = {'id':None,
  1594. 'name':None,
  1595. 'mixed':0,
  1596. 'abstract':0,
  1597. 'block':lambda: self._parent.parent().getBlockDefault(),
  1598. 'final':lambda: self._parent.parent().getFinalDefault()}
  1599. contents = {'xsd':['annotation', 'simpleContent', 'complexContent',\
  1600. 'group', 'all', 'choice', 'sequence', 'attribute', 'attributeGroup',\
  1601. 'anyAttribute', 'any']}
  1602. def __init__(self, parent):
  1603. XMLSchemaComponent.__init__(self, parent)
  1604. self.annotation = None
  1605. self.content = None
  1606. self.attr_content = None
  1607. def fromDom(self, node):
  1608. self.setAttributes(node)
  1609. contents = self.getContents(node)
  1610. indx = 0
  1611. num = len(contents)
  1612. #XXX ugly
  1613. if not num:
  1614. return
  1615. component = SplitQName(contents[indx].getTagName())[1]
  1616. if component == 'annotation':
  1617. self.annotation = Annotation(self)
  1618. self.annotation.fromDom(contents[indx])
  1619. indx += 1
  1620. component = SplitQName(contents[indx].getTagName())[1]
  1621. self.content = None
  1622. if component == 'simpleContent':
  1623. self.content = self.__class__.SimpleContent(self)
  1624. self.content.fromDom(contents[indx])
  1625. elif component == 'complexContent':
  1626. self.content = self.__class__.ComplexContent(self)
  1627. self.content.fromDom(contents[indx])
  1628. else:
  1629. if component == 'all':
  1630. self.content = All(self)
  1631. elif component == 'choice':
  1632. self.content = Choice(self)
  1633. elif component == 'sequence':
  1634. self.content = Sequence(self)
  1635. elif component == 'group':
  1636. self.content = ModelGroupReference(self)
  1637. if self.content:
  1638. self.content.fromDom(contents[indx])
  1639. indx += 1
  1640. self.attr_content = []
  1641. while indx < num:
  1642. component = SplitQName(contents[indx].getTagName())[1]
  1643. if component == 'attribute':
  1644. if contents[indx].hasattr('ref'):
  1645. self.attr_content.append(AttributeReference(self))
  1646. else:
  1647. self.attr_content.append(LocalAttributeDeclaration(self))
  1648. elif component == 'attributeGroup':
  1649. self.attr_content.append(AttributeGroupDefinition(self))
  1650. elif component == 'anyAttribute':
  1651. self.attr_content.append(AttributeWildCard(self))
  1652. else:
  1653. raise SchemaError, 'Unknown component (%s)' %(contents[indx].getTagName())
  1654. self.attr_content[-1].fromDom(contents[indx])
  1655. indx += 1
  1656. class _DerivedType(XMLSchemaComponent):
  1657. def __init__(self, parent):
  1658. XMLSchemaComponent.__init__(self, parent)
  1659. self.annotation = None
  1660. self.derivation = None
  1661. def fromDom(self, node):
  1662. self.setAttributes(node)
  1663. contents = self.getContents(node)
  1664. for i in contents:
  1665. component = SplitQName(i.getTagName())[1]
  1666. if component in self.__class__.contents['xsd']:
  1667. if component == 'annotation' and not self.annotation:
  1668. self.annotation = Annotation(self)
  1669. self.annotation.fromDom(i)
  1670. continue
  1671. elif component == 'restriction' and not self.derivation:
  1672. self.derivation = self.__class__.Restriction(self)
  1673. elif component == 'extension' and not self.derivation:
  1674. self.derivation = self.__class__.Extension(self)
  1675. else:
  1676. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1677. else:
  1678. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1679. self.derivation.fromDom(i)
  1680. class ComplexContent(_DerivedType,\
  1681. MarkerInterface,\
  1682. ComplexMarker):
  1683. """<complexContent>
  1684. parents:
  1685. complexType
  1686. attributes:
  1687. id -- ID
  1688. mixed -- boolean, false
  1689. contents:
  1690. annotation?, (restriction | extension)
  1691. """
  1692. attributes = {'id':None,
  1693. 'mixed':0 }
  1694. contents = {'xsd':['annotation', 'restriction', 'extension']}
  1695. class _DerivationBase(XMLSchemaComponent):
  1696. """<extension>,<restriction>
  1697. parents:
  1698. complexContent
  1699. attributes:
  1700. id -- ID
  1701. base -- QName, required
  1702. contents:
  1703. annotation?, (group | all | choice | sequence)?,
  1704. (attribute | attributeGroup)*, anyAttribute?
  1705. """
  1706. required = ['base']
  1707. attributes = {'id':None,
  1708. 'base':None }
  1709. contents = {'xsd':['annotation', 'group', 'all', 'choice',\
  1710. 'sequence', 'attribute', 'attributeGroup', 'anyAttribute']}
  1711. def fromDom(self, node):
  1712. self.setAttributes(node)
  1713. contents = self.getContents(node)
  1714. indx = 0
  1715. num = len(contents)
  1716. #XXX ugly
  1717. if not num:
  1718. return
  1719. component = SplitQName(contents[indx].getTagName())[1]
  1720. if component == 'annotation':
  1721. self.annotation = Annotation(self)
  1722. self.annotation.fromDom(contents[indx])
  1723. indx += 1
  1724. component = SplitQName(contents[indx].getTagName())[1]
  1725. if component == 'all':
  1726. self.content = All(self)
  1727. self.content.fromDom(contents[indx])
  1728. elif component == 'choice':
  1729. self.content = Choice(self)
  1730. self.content.fromDom(contents[indx])
  1731. elif component == 'sequence':
  1732. self.content = Sequence(self)
  1733. self.content.fromDom(contents[indx])
  1734. elif component == 'group':
  1735. self.content = ModelGroupReference(self)
  1736. self.content.fromDom(contents[indx])
  1737. else:
  1738. self.content = None
  1739. indx += 1
  1740. self.attr_content = []
  1741. while indx < num:
  1742. component = SplitQName(contents[indx].getTagName())[1]
  1743. if component == 'attribute':
  1744. if contents[indx].hasattr('ref'):
  1745. self.attr_content.append(AttributeReference(self))
  1746. else:
  1747. self.attr_content.append(LocalAttributeDeclaration(self))
  1748. elif component == 'attributeGroup':
  1749. self.attr_content.append(AttributeGroupDefinition(self))
  1750. elif component == 'anyAttribute':
  1751. self.attr_content.append(AttributeWildCard(self))
  1752. else:
  1753. raise SchemaError, 'Unknown component (%s)' %(contents[indx].getTagName())
  1754. self.attr_content[-1].fromDom(contents[indx])
  1755. indx += 1
  1756. class Extension(_DerivationBase, MarkerInterface, ExtensionMarker):
  1757. """<extension base>
  1758. parents:
  1759. complexContent
  1760. attributes:
  1761. id -- ID
  1762. base -- QName, required
  1763. contents:
  1764. annotation?, (group | all | choice | sequence)?,
  1765. (attribute | attributeGroup)*, anyAttribute?
  1766. """
  1767. pass
  1768. class Restriction(_DerivationBase,\
  1769. MarkerInterface,\
  1770. RestrictionMarker):
  1771. """<restriction base>
  1772. parents:
  1773. complexContent
  1774. attributes:
  1775. id -- ID
  1776. base -- QName, required
  1777. contents:
  1778. annotation?, (group | all | choice | sequence)?,
  1779. (attribute | attributeGroup)*, anyAttribute?
  1780. """
  1781. pass
  1782. class SimpleContent(_DerivedType,\
  1783. MarkerInterface,\
  1784. SimpleMarker):
  1785. """<simpleContent>
  1786. parents:
  1787. complexType
  1788. attributes:
  1789. id -- ID
  1790. contents:
  1791. annotation?, (restriction | extension)
  1792. """
  1793. attributes = {'id':None}
  1794. contents = {'xsd':['annotation', 'restriction', 'extension']}
  1795. class Extension(XMLSchemaComponent,\
  1796. MarkerInterface,\
  1797. ExtensionMarker):
  1798. """<extension base>
  1799. parents:
  1800. simpleContent
  1801. attributes:
  1802. id -- ID
  1803. base -- QName, required
  1804. contents:
  1805. annotation?, (group | all | choice | sequence)?,
  1806. (attribute | attributeGroup)*, anyAttribute?
  1807. """
  1808. required = ['base']
  1809. attributes = {'id':None,
  1810. 'base':None }
  1811. contents = {'xsd':['annotation', 'group', 'all', 'choice',\
  1812. 'sequence', 'attribute', 'attributeGroup', 'anyAttribute']}
  1813. def fromDom(self, node):
  1814. self.setAttributes(node)
  1815. contents = self.getContents(node)
  1816. indx = 0
  1817. num = len(contents)
  1818. component = SplitQName(contents[indx].getTagName())[1]
  1819. if component == 'annotation':
  1820. self.annotation = Annotation(self)
  1821. self.annotation.fromDom(contents[indx])
  1822. indx += 1
  1823. component = SplitQName(contents[indx].getTagName())[1]
  1824. if component == 'all':
  1825. self.content = All(self)
  1826. elif component == 'choice':
  1827. self.content = Choice(self)
  1828. elif component == 'sequence':
  1829. self.content = Sequence(self)
  1830. elif component == 'group':
  1831. self.content = ModelGroupReference(self)
  1832. else:
  1833. raise SchemaError, 'Unknown component (%s)' %(contents[indx].getTagName())
  1834. self.content.fromDom(contents[indx])
  1835. indx += 1
  1836. self.attr_content = []
  1837. while indx < num:
  1838. component = SplitQName(contents[indx].getTagName())[1]
  1839. if component == 'attribute':
  1840. if contents[indx].hasattr('ref'):
  1841. self.attr_content.append(AttributeReference(self))
  1842. else:
  1843. self.attr_content.append(LocalAttributeDeclaration(self))
  1844. elif component == 'attributeGroup':
  1845. self.attr_content.append(AttributeGroupDefinition(self))
  1846. elif component == 'anyAttribute':
  1847. self.attr_content.append(AttributeWildCard(self))
  1848. else:
  1849. raise SchemaError, 'Unknown component (%s)' %(contents[indx].getTagName())
  1850. self.attr_content[-1].fromDom(contents[indx])
  1851. indx += 1
  1852. class Restriction(XMLSchemaComponent,\
  1853. MarkerInterface,\
  1854. RestrictionMarker):
  1855. """<restriction base>
  1856. parents:
  1857. simpleContent
  1858. attributes:
  1859. id -- ID
  1860. base -- QName, required
  1861. contents:
  1862. annotation?, simpleType?, (enumeration | length |
  1863. maxExclusive | maxInclusive | maxLength | minExclusive |
  1864. minInclusive | minLength | pattern | fractionDigits |
  1865. totalDigits | whiteSpace)*, (attribute | attributeGroup)*,
  1866. anyAttribute?
  1867. """
  1868. required = ['base']
  1869. attributes = {'id':None,
  1870. 'base':None }
  1871. contents = {'xsd':['annotation', 'simpleType', 'attribute',\
  1872. 'attributeGroup', 'anyAttribute'] + RestrictionMarker.facets}
  1873. class LocalComplexType(ComplexType):
  1874. """<complexType>
  1875. parents:
  1876. element
  1877. attributes:
  1878. id -- ID
  1879. mixed -- boolean, false
  1880. contents:
  1881. annotation?, (simpleContent | complexContent |
  1882. ((group | all | choice | sequence)?, (attribute | attributeGroup)*, anyAttribute?))
  1883. """
  1884. required = []
  1885. attributes = {'id':None,
  1886. 'mixed':0}
  1887. class SimpleType(XMLSchemaComponent,\
  1888. MarkerInterface,\
  1889. DefinitionMarker,\
  1890. SimpleMarker):
  1891. """<simpleType name>
  1892. parents:
  1893. redefine, schema
  1894. attributes:
  1895. id -- ID
  1896. name -- NCName, required
  1897. final -- ('#all' | ('extension' | 'restriction' | 'list' | 'union')*),
  1898. schema.finalDefault
  1899. contents:
  1900. annotation?, (restriction | list | union)
  1901. """
  1902. required = ['name']
  1903. attributes = {'id':None,
  1904. 'name':None,
  1905. 'final':lambda: self._parent.parent().getFinalDefault()}
  1906. contents = {'xsd':['annotation', 'restriction', 'list', 'union']}
  1907. def __init__(self, parent):
  1908. XMLSchemaComponent.__init__(self, parent)
  1909. self.annotation = None
  1910. self.content = None
  1911. self.attr_content = None
  1912. def setType(self, qname, namespace):
  1913. self.type = TypeDescriptionComponent(namespace, qname)
  1914. def fromDom(self, node):
  1915. self.setAttributes(node)
  1916. contents = self.getContents(node)
  1917. for child in contents:
  1918. component = SplitQName(child.getTagName())[1]
  1919. if component == 'annotation':
  1920. self.annotation = Annotation(self)
  1921. self.annotation.fromDom(child)
  1922. break
  1923. else:
  1924. return
  1925. if component == 'restriction':
  1926. self.content = self.__class__.Restriction(self)
  1927. elif component == 'list':
  1928. self.content = self.__class__.List(self)
  1929. elif component == 'union':
  1930. self.content = self.__class__.Union(self)
  1931. else:
  1932. raise SchemaError, 'Unknown component (%s)' %(contents[indx].getTagName())
  1933. self.content.fromDom(child)
  1934. class Restriction(XMLSchemaComponent,\
  1935. MarkerInterface,\
  1936. RestrictionMarker):
  1937. """<restriction base>
  1938. parents:
  1939. simpleType
  1940. attributes:
  1941. id -- ID
  1942. base -- QName, required or simpleType child
  1943. contents:
  1944. annotation?, simpleType?, (enumeration | length |
  1945. maxExclusive | maxInclusive | maxLength | minExclusive |
  1946. minInclusive | minLength | pattern | fractionDigits |
  1947. totalDigits | whiteSpace)*
  1948. """
  1949. attributes = {'id':None,
  1950. 'base':None }
  1951. contents = {'xsd':['annotation', 'simpleType']+RestrictionMarker.facets}
  1952. def __init__(self, parent):
  1953. XMLSchemaComponent.__init__(self, parent)
  1954. self.annotation = None
  1955. self.content = None
  1956. self.attr_content = None
  1957. def fromDom(self, node):
  1958. self.setAttributes(node)
  1959. contents = self.getContents(node)
  1960. self.content = []
  1961. self.attr_content = []
  1962. for indx in range(len(contents)):
  1963. component = SplitQName(contents[indx].getTagName())[1]
  1964. if (component == 'annotation') and (not indx):
  1965. self.annotation = Annotation(self)
  1966. self.annotation.fromDom(contents[indx])
  1967. continue
  1968. elif (component == 'simpleType') and (not indx or indx == 1):
  1969. self.content.append(SimpleType(self))
  1970. self.content[-1].fromDom(contents[indx])
  1971. elif component in RestrictionMarker.facets:
  1972. #print_debug('%s class instance, skipping %s' %(self.__class__, component))
  1973. pass
  1974. else:
  1975. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1976. class Union(XMLSchemaComponent):
  1977. """<union>
  1978. parents:
  1979. simpleType
  1980. attributes:
  1981. id -- ID
  1982. memberTypes -- list of QNames, required or simpleType child.
  1983. contents:
  1984. annotation?, simpleType*
  1985. """
  1986. attributes = {'id':None,
  1987. 'memberTypes':None }
  1988. contents = {'xsd':['annotation', 'simpleType']}
  1989. class List(XMLSchemaComponent):
  1990. """<union>
  1991. parents:
  1992. simpleType
  1993. attributes:
  1994. id -- ID
  1995. itemType -- QName, required or simpleType child.
  1996. contents:
  1997. annotation?, simpleType?
  1998. """
  1999. attributes = {'id':None,
  2000. 'memberTypes':None }
  2001. contents = {'xsd':['annotation', 'simpleType']}
  2002. class AnonymousSimpleType(SimpleType,\
  2003. MarkerInterface,\
  2004. SimpleMarker):
  2005. """<simpleType>
  2006. parents:
  2007. attribute, element, list, restriction, union
  2008. attributes:
  2009. id -- ID
  2010. contents:
  2011. annotation?, (restriction | list | union)
  2012. """
  2013. required = []
  2014. attributes = {'id':None}
  2015. class Redefine:
  2016. """<redefine>
  2017. parents:
  2018. attributes:
  2019. contents:
  2020. """
  2021. pass
  2022. ###########################
  2023. ###########################
  2024. if sys.version_info[:2] >= (2, 2):
  2025. tupleClass = tuple
  2026. else:
  2027. import UserTuple
  2028. tupleClass = UserTuple.UserTuple
  2029. class TypeDescriptionComponent(tupleClass):
  2030. """Tuple of length 2, consisting of
  2031. a namespace and unprefixed name.
  2032. """
  2033. def __init__(self, args):
  2034. """args -- (namespace, name)
  2035. Remove the name's prefix, irrelevant.
  2036. """
  2037. if len(args) != 2:
  2038. raise TypeError, 'expecting tuple (namespace, name), got %s' %args
  2039. elif args[1].find(':') >= 0:
  2040. args = (args[0], SplitQName(args[1])[1])
  2041. tuple.__init__(self, args)
  2042. return
  2043. def getTargetNamespace(self):
  2044. return self[0]
  2045. def getName(self):
  2046. return self[1]
  2047. '''
  2048. import string, types, base64, re
  2049. from Utility import DOM, Collection
  2050. from StringIO import StringIO
  2051. class SchemaReader:
  2052. """A SchemaReader creates XMLSchema objects from urls and xml data."""
  2053. def loadFromStream(self, file):
  2054. """Return an XMLSchema instance loaded from a file object."""
  2055. document = DOM.loadDocument(file)
  2056. schema = XMLSchema()
  2057. schema.load(document)
  2058. return schema
  2059. def loadFromString(self, data):
  2060. """Return an XMLSchema instance loaded from an xml string."""
  2061. return self.loadFromStream(StringIO(data))
  2062. def loadFromURL(self, url):
  2063. """Return an XMLSchema instance loaded from the given url."""
  2064. document = DOM.loadFromURL(url)
  2065. schema = XMLSchema()
  2066. schema.location = url
  2067. schema.load(document)
  2068. return schema
  2069. def loadFromFile(self, filename):
  2070. """Return an XMLSchema instance loaded from the given file."""
  2071. file = open(filename, 'rb')
  2072. try: schema = self.loadFromStream(file)
  2073. finally: file.close()
  2074. return schema
  2075. class SchemaError(Exception):
  2076. pass
  2077. class XMLSchema:
  2078. # This is temporary, for the benefit of WSDL until the real thing works.
  2079. def __init__(self, element):
  2080. self.targetNamespace = DOM.getAttr(element, 'targetNamespace')
  2081. self.element = element
  2082. class realXMLSchema:
  2083. """A schema is a collection of schema components derived from one
  2084. or more schema documents, that is, one or more <schema> element
  2085. information items. It represents the abstract notion of a schema
  2086. rather than a single schema document (or other representation)."""
  2087. def __init__(self):
  2088. self.simpleTypes = Collection(self)
  2089. self.complexTypes = Collection(self)
  2090. self.attributes = Collection(self)
  2091. self.elements = Collection(self)
  2092. self.attrGroups = Collection(self)
  2093. self.idConstraints=None
  2094. self.modelGroups = None
  2095. self.notations = None
  2096. self.extensions = []
  2097. targetNamespace = None
  2098. attributeFormDefault = 'unqualified'
  2099. elementFormDefault = 'unqualified'
  2100. blockDefault = None
  2101. finalDefault = None
  2102. location = None
  2103. version = None
  2104. id = None
  2105. def load(self, document):
  2106. if document.nodeType == document.DOCUMENT_NODE:
  2107. schema = DOM.getElement(document, 'schema', None, None)
  2108. else:
  2109. schema = document
  2110. if schema is None:
  2111. raise SchemaError('Missing <schema> element.')
  2112. self.namespace = namespace = schema.namespaceURI
  2113. if not namespace in DOM.NS_XSD_ALL:
  2114. raise SchemaError(
  2115. 'Unknown XML schema namespace: %s.' % self.namespace
  2116. )
  2117. for attrname in (
  2118. 'targetNamespace', 'attributeFormDefault', 'elementFormDefault',
  2119. 'blockDefault', 'finalDefault', 'version', 'id'
  2120. ):
  2121. value = DOM.getAttr(schema, attrname, None, None)
  2122. if value is not None:
  2123. setattr(self, attrname, value)
  2124. # Resolve imports and includes here?
  2125. ## imported = {}
  2126. ## while 1:
  2127. ## imports = []
  2128. ## for element in DOM.getElements(definitions, 'import', NS_WSDL):
  2129. ## location = DOM.getAttr(element, 'location')
  2130. ## if not imported.has_key(location):
  2131. ## imports.append(element)
  2132. ## if not imports:
  2133. ## break
  2134. ## for element in imports:
  2135. ## self._import(document, element)
  2136. ## imported[location] = 1
  2137. for element in DOM.getElements(schema, None, None):
  2138. localName = element.localName
  2139. if not DOM.nsUriMatch(element.namespaceURI, namespace):
  2140. self.extensions.append(element)
  2141. continue
  2142. elif localName == 'message':
  2143. name = DOM.getAttr(element, 'name')
  2144. docs = GetDocumentation(element)
  2145. message = self.addMessage(name, docs)
  2146. parts = DOM.getElements(element, 'part', NS_WSDL)
  2147. message.load(parts)
  2148. continue
  2149. def _import(self, document, element):
  2150. namespace = DOM.getAttr(element, 'namespace', default=None)
  2151. location = DOM.getAttr(element, 'location', default=None)
  2152. if namespace is None or location is None:
  2153. raise WSDLError(
  2154. 'Invalid import element (missing namespace or location).'
  2155. )
  2156. # Sort-of support relative locations to simplify unit testing. The
  2157. # WSDL specification actually doesn't allow relative URLs, so its
  2158. # ok that this only works with urls relative to the initial document.
  2159. location = urllib.basejoin(self.location, location)
  2160. obimport = self.addImport(namespace, location)
  2161. obimport._loaded = 1
  2162. importdoc = DOM.loadFromURL(location)
  2163. try:
  2164. if location.find('#') > -1:
  2165. idref = location.split('#')[-1]
  2166. imported = DOM.getElementById(importdoc, idref)
  2167. else:
  2168. imported = importdoc.documentElement
  2169. if imported is None:
  2170. raise WSDLError(
  2171. 'Import target element not found for: %s' % location
  2172. )
  2173. imported_tns = DOM.getAttr(imported, 'targetNamespace')
  2174. importer_tns = namespace
  2175. if imported_tns != importer_tns:
  2176. return
  2177. if imported.localName == 'definitions':
  2178. imported_nodes = imported.childNodes
  2179. else:
  2180. imported_nodes = [imported]
  2181. parent = element.parentNode
  2182. for node in imported_nodes:
  2183. if node.nodeType != node.ELEMENT_NODE:
  2184. continue
  2185. child = DOM.importNode(document, node, 1)
  2186. parent.appendChild(child)
  2187. child.setAttribute('targetNamespace', importer_tns)
  2188. attrsNS = imported._attrsNS
  2189. for attrkey in attrsNS.keys():
  2190. if attrkey[0] == DOM.NS_XMLNS:
  2191. attr = attrsNS[attrkey].cloneNode(1)
  2192. child.setAttributeNode(attr)
  2193. finally:
  2194. importdoc.unlink()
  2195. class Element:
  2196. """Common base class for element representation classes."""
  2197. def __init__(self, name=None, documentation=''):
  2198. self.name = name
  2199. self.documentation = documentation
  2200. self.extensions = []
  2201. def addExtension(self, item):
  2202. self.extensions.append(item)
  2203. class SimpleTypeDefinition:
  2204. """Represents an xml schema simple type definition."""
  2205. class ComplexTypeDefinition:
  2206. """Represents an xml schema complex type definition."""
  2207. class AttributeDeclaration:
  2208. """Represents an xml schema attribute declaration."""
  2209. class ElementDeclaration:
  2210. """Represents an xml schema element declaration."""
  2211. def __init__(self, name, type=None, targetNamespace=None):
  2212. self.name = name
  2213. targetNamespace = None
  2214. annotation = None
  2215. nillable = 0
  2216. abstract = 0
  2217. default = None
  2218. fixed = None
  2219. scope = 'global'
  2220. type = None
  2221. form = 0
  2222. # Things we will not worry about for now.
  2223. id_constraint_defs = None
  2224. sub_group_exclude = None
  2225. sub_group_affils = None
  2226. disallowed_subs = None
  2227. class AttributeGroupDefinition:
  2228. """Represents an xml schema attribute group definition."""
  2229. class IdentityConstraintDefinition:
  2230. """Represents an xml schema identity constraint definition."""
  2231. class ModelGroupDefinition:
  2232. """Represents an xml schema model group definition."""
  2233. class NotationDeclaration:
  2234. """Represents an xml schema notation declaration."""
  2235. class Annotation:
  2236. """Represents an xml schema annotation."""
  2237. class ModelGroup:
  2238. """Represents an xml schema model group."""
  2239. class Particle:
  2240. """Represents an xml schema particle."""
  2241. class WildCard:
  2242. """Represents an xml schema wildcard."""
  2243. class AttributeUse:
  2244. """Represents an xml schema attribute use."""
  2245. class ElementComponent:
  2246. namespace = ''
  2247. name = ''
  2248. type = None
  2249. form = 'qualified | unqualified'
  2250. scope = 'global or complex def'
  2251. constraint = ('value', 'default | fixed')
  2252. nillable = 0
  2253. id_constraint_defs = None
  2254. sub_group_affil = None
  2255. sub_group_exclusions = None
  2256. disallowed_subs = 'substitution, extension, restriction'
  2257. abstract = 0
  2258. minOccurs = 1
  2259. maxOccurs = 1
  2260. ref = ''
  2261. class AttributeThing:
  2262. name = ''
  2263. namespace = ''
  2264. typeName = ''
  2265. typeUri = ''
  2266. scope = 'global | local to complex def'
  2267. constraint = ('value:default', 'value:fixed')
  2268. use = 'optional | prohibited | required'
  2269. class ElementDataType:
  2270. namespace = ''
  2271. name = ''
  2272. element_form = 'qualified | unqualified'
  2273. attr_form = None
  2274. type_name = ''
  2275. type_uri = ''
  2276. def __init__(self, name, namespace, type_name, type_uri):
  2277. self.namespace = namespace
  2278. self.name = name
  2279. # type may be anonymous...
  2280. self.type_name = type_name
  2281. self.type_uri = type_uri
  2282. def checkValue(self, value, context):
  2283. # Delegate value checking to the type of the element.
  2284. typeref = (self.type_uri, self.type_name)
  2285. handler = context.serializer.getType(typeref)
  2286. return handler.checkValue(value, context)
  2287. def serialize(self, name, namespace, value, context, **kwargs):
  2288. if context.check_values:
  2289. self.checkValue(value, context)
  2290. # Delegate serialization to the type of the element.
  2291. typeref = (self.type_uri, self.type_name)
  2292. handler = context.serializer.getType(typeref)
  2293. return handler.serialize(self.name, self.namespace, value, context)
  2294. def deserialize(self, element, context):
  2295. if element_is_null(element, context):
  2296. return None
  2297. # Delegate deserialization to the type of the element.
  2298. typeref = (self.type_uri, self.type_name)
  2299. handler = context.serializer.getType(typeref)
  2300. return handler.deserialize(element, context)
  2301. def parse_schema(data):
  2302. targetNS = ''
  2303. attributeFormDefault = 0
  2304. elementFormDefault = 0
  2305. blockDefault = ''
  2306. finalDefault = ''
  2307. language = None
  2308. version = None
  2309. id = ''
  2310. '''