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.
 
 
 

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