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.
 
 
 

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