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.
 
 
 

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