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.
 
 
 

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