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.
 
 
 

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