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.
 
 
 

3028 lines
104 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. tp.loadSchema(schema)
  989. else:
  990. tp._schema = schema
  991. if self.getImportSchemas().has_key(import_ns):
  992. warnings.warn(\
  993. 'Detected multiple imports of the namespace "%s" '\
  994. %import_ns)
  995. self.addImportSchema(schema)
  996. # spec says can have multiple imports of same namespace
  997. # but purpose of import is just dependency declaration.
  998. self.imports[import_ns] = tp
  999. elif component == 'redefine':
  1000. warnings.warn('redefine is ignored')
  1001. elif component == 'annotation':
  1002. warnings.warn('annotation is ignored')
  1003. elif component == 'attribute':
  1004. tp = AttributeDeclaration(self)
  1005. tp.fromDom(childNode)
  1006. self.attr_decl[tp.getAttribute('name')] = tp
  1007. elif component == 'attributeGroup':
  1008. tp = AttributeGroupDefinition(self)
  1009. tp.fromDom(childNode)
  1010. self.attr_groups[tp.getAttribute('name')] = tp
  1011. elif component == 'element':
  1012. tp = ElementDeclaration(self)
  1013. tp.fromDom(childNode)
  1014. self.elements[tp.getAttribute('name')] = tp
  1015. elif component == 'group':
  1016. tp = ModelGroupDefinition(self)
  1017. tp.fromDom(childNode)
  1018. self.model_groups[tp.getAttribute('name')] = tp
  1019. elif component == 'notation':
  1020. tp = Notation(self)
  1021. tp.fromDom(childNode)
  1022. self.notations[tp.getAttribute('name')] = tp
  1023. elif component == 'complexType':
  1024. tp = ComplexType(self)
  1025. tp.fromDom(childNode)
  1026. self.types[tp.getAttribute('name')] = tp
  1027. elif component == 'simpleType':
  1028. tp = SimpleType(self)
  1029. tp.fromDom(childNode)
  1030. self.types[tp.getAttribute('name')] = tp
  1031. else:
  1032. break
  1033. # slocd = SchemaReader.namespaceToSchema
  1034. #
  1035. # print "XMLSchema(%d): %s" %(id(self), self.targetNamespace)
  1036. #
  1037. # for node in imports:
  1038. # tp = self.__class__.Import(self)
  1039. # tp.fromDom(node)
  1040. #
  1041. # import_ns = tp.getAttribute('namespace') or \
  1042. # self.__class__.empty_namespace
  1043. #
  1044. # print "<import namespace=%s>" %import_ns
  1045. #
  1046. # schema = slocd.get(import_ns)
  1047. # if schema is None:
  1048. # schema = XMLSchema()
  1049. # slocd[import_ns] = schema
  1050. # tp.loadSchema(schema)
  1051. # else:
  1052. # tp._schema = schema
  1053. #
  1054. # if self.getImportSchemas().has_key(import_ns):
  1055. # warnings.warn(\
  1056. # 'Detected multiple imports of the namespace "%s",'+
  1057. # 'may cause problems if they have different schemaLocations.' %import_ns
  1058. # )
  1059. # raise RuntimeError, 'hi'
  1060. #
  1061. # self.addImportSchema(schema)
  1062. # self.imports[import_ns] = tp
  1063. class Import(XMLSchemaComponent):
  1064. """<import>
  1065. parent:
  1066. schema
  1067. attributes:
  1068. id -- ID
  1069. namespace -- anyURI
  1070. schemaLocation -- anyURI
  1071. contents:
  1072. annotation?
  1073. """
  1074. attributes = {'id':None,
  1075. 'namespace':None,
  1076. 'schemaLocation':None}
  1077. contents = {'xsd':['annotation']}
  1078. tag = 'import'
  1079. def __init__(self, parent):
  1080. XMLSchemaComponent.__init__(self, parent)
  1081. self.annotation = None
  1082. self._schema = None
  1083. def fromDom(self, node):
  1084. self.setAttributes(node)
  1085. contents = self.getContents(node)
  1086. if self.attributes['namespace'] == self.getTargetNamespace():
  1087. raise SchemaError, 'namespace of schema and import match'
  1088. for i in contents:
  1089. component = SplitQName(i.getTagName())[1]
  1090. if component == 'annotation' and not self.annotation:
  1091. self.annotation = Annotation(self)
  1092. self.annotation.fromDom(i)
  1093. else:
  1094. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1095. def getSchema(self):
  1096. """if schema is not defined, first look for a Schema class instance
  1097. in parent Schema. Else if not defined resolve schemaLocation
  1098. and create a new Schema class instance, and keep a hard reference.
  1099. """
  1100. if not self._schema:
  1101. ns = self.attributes['namespace']
  1102. schema = self._parent().getImportSchemas().get(ns)
  1103. if not schema and self._parent()._parent:
  1104. schema = self._parent()._parent().getImportSchemas().get(ns)
  1105. if not schema:
  1106. url = self.attributes.get('schemaLocation')
  1107. if not url:
  1108. raise SchemaError, 'namespace(%s) is unknown' %ns
  1109. base_url = self._parent().getBaseUrl()
  1110. reader = SchemaReader(base_url=base_url)
  1111. reader._imports = self._parent().getImportSchemas()
  1112. reader._includes = self._parent().getIncludeSchemas()
  1113. self._schema = reader.loadFromURL(url)
  1114. return self._schema or schema
  1115. def loadSchema(self, schema):
  1116. """
  1117. """
  1118. base_url = self._parent().getBaseUrl()
  1119. reader = SchemaReader(base_url=base_url)
  1120. reader._imports = self._parent().getImportSchemas()
  1121. reader._includes = self._parent().getIncludeSchemas()
  1122. self._schema = schema
  1123. reader.loadFromURL(self.attributes.get('schemaLocation'), schema)
  1124. class Include(XMLSchemaComponent):
  1125. """<include schemaLocation>
  1126. parent:
  1127. schema
  1128. attributes:
  1129. id -- ID
  1130. schemaLocation -- anyURI, required
  1131. contents:
  1132. annotation?
  1133. """
  1134. required = ['schemaLocation']
  1135. attributes = {'id':None,
  1136. 'schemaLocation':None}
  1137. contents = {'xsd':['annotation']}
  1138. tag = 'include'
  1139. def __init__(self, parent):
  1140. XMLSchemaComponent.__init__(self, parent)
  1141. self.annotation = None
  1142. self._schema = None
  1143. def fromDom(self, node):
  1144. self.setAttributes(node)
  1145. contents = self.getContents(node)
  1146. for i in contents:
  1147. component = SplitQName(i.getTagName())[1]
  1148. if component == 'annotation' and not self.annotation:
  1149. self.annotation = Annotation(self)
  1150. self.annotation.fromDom(i)
  1151. else:
  1152. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1153. def getSchema(self):
  1154. """if schema is not defined, first look for a Schema class instance
  1155. in parent Schema. Else if not defined resolve schemaLocation
  1156. and create a new Schema class instance.
  1157. """
  1158. if not self._schema:
  1159. schema = self._parent()
  1160. self._schema = schema.getIncludeSchemas().get(\
  1161. self.attributes['schemaLocation']
  1162. )
  1163. if not self._schema:
  1164. url = self.attributes['schemaLocation']
  1165. reader = SchemaReader(base_url=schema.getBaseUrl())
  1166. reader._imports = schema.getImportSchemas()
  1167. reader._includes = schema.getIncludeSchemas()
  1168. self._schema = reader.loadFromURL(url)
  1169. return self._schema
  1170. class AttributeDeclaration(XMLSchemaComponent,\
  1171. AttributeMarker,\
  1172. DeclarationMarker):
  1173. """<attribute name>
  1174. parent:
  1175. schema
  1176. attributes:
  1177. id -- ID
  1178. name -- NCName, required
  1179. type -- QName
  1180. default -- string
  1181. fixed -- string
  1182. contents:
  1183. annotation?, simpleType?
  1184. """
  1185. required = ['name']
  1186. attributes = {'id':None,
  1187. 'name':None,
  1188. 'type':None,
  1189. 'default':None,
  1190. 'fixed':None}
  1191. contents = {'xsd':['annotation','simpleType']}
  1192. tag = 'attribute'
  1193. def __init__(self, parent):
  1194. XMLSchemaComponent.__init__(self, parent)
  1195. self.annotation = None
  1196. self.content = None
  1197. def fromDom(self, node):
  1198. """ No list or union support
  1199. """
  1200. self.setAttributes(node)
  1201. contents = self.getContents(node)
  1202. for i in contents:
  1203. component = SplitQName(i.getTagName())[1]
  1204. if component == 'annotation' and not self.annotation:
  1205. self.annotation = Annotation(self)
  1206. self.annotation.fromDom(i)
  1207. elif component == 'simpleType':
  1208. self.content = AnonymousSimpleType(self)
  1209. self.content.fromDom(i)
  1210. else:
  1211. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1212. class LocalAttributeDeclaration(AttributeDeclaration,\
  1213. AttributeMarker,\
  1214. LocalMarker,\
  1215. DeclarationMarker):
  1216. """<attribute name>
  1217. parent:
  1218. complexType, restriction, extension, attributeGroup
  1219. attributes:
  1220. id -- ID
  1221. name -- NCName, required
  1222. type -- QName
  1223. form -- ('qualified' | 'unqualified'), schema.attributeFormDefault
  1224. use -- ('optional' | 'prohibited' | 'required'), optional
  1225. default -- string
  1226. fixed -- string
  1227. contents:
  1228. annotation?, simpleType?
  1229. """
  1230. required = ['name']
  1231. attributes = {'id':None,
  1232. 'name':None,
  1233. 'type':None,
  1234. 'form':lambda self: GetSchema(self).getAttributeFormDefault(),
  1235. 'use':'optional',
  1236. 'default':None,
  1237. 'fixed':None}
  1238. contents = {'xsd':['annotation','simpleType']}
  1239. def __init__(self, parent):
  1240. AttributeDeclaration.__init__(self, parent)
  1241. self.annotation = None
  1242. self.content = None
  1243. def fromDom(self, node):
  1244. self.setAttributes(node)
  1245. contents = self.getContents(node)
  1246. for i in contents:
  1247. component = SplitQName(i.getTagName())[1]
  1248. if component == 'annotation' and not self.annotation:
  1249. self.annotation = Annotation(self)
  1250. self.annotation.fromDom(i)
  1251. elif component == 'simpleType':
  1252. self.content = AnonymousSimpleType(self)
  1253. self.content.fromDom(i)
  1254. else:
  1255. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1256. class AttributeWildCard(XMLSchemaComponent,\
  1257. AttributeMarker,\
  1258. DeclarationMarker,\
  1259. WildCardMarker):
  1260. """<anyAttribute>
  1261. parents:
  1262. complexType, restriction, extension, attributeGroup
  1263. attributes:
  1264. id -- ID
  1265. namespace -- '##any' | '##other' |
  1266. (anyURI* | '##targetNamespace' | '##local'), ##any
  1267. processContents -- 'lax' | 'skip' | 'strict', strict
  1268. contents:
  1269. annotation?
  1270. """
  1271. attributes = {'id':None,
  1272. 'namespace':'##any',
  1273. 'processContents':'strict'}
  1274. contents = {'xsd':['annotation']}
  1275. tag = 'anyAttribute'
  1276. def __init__(self, parent):
  1277. XMLSchemaComponent.__init__(self, parent)
  1278. self.annotation = None
  1279. def fromDom(self, node):
  1280. self.setAttributes(node)
  1281. contents = self.getContents(node)
  1282. for i in contents:
  1283. component = SplitQName(i.getTagName())[1]
  1284. if component == 'annotation' and not self.annotation:
  1285. self.annotation = Annotation(self)
  1286. self.annotation.fromDom(i)
  1287. else:
  1288. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1289. class AttributeReference(XMLSchemaComponent,\
  1290. AttributeMarker,\
  1291. ReferenceMarker):
  1292. """<attribute ref>
  1293. parents:
  1294. complexType, restriction, extension, attributeGroup
  1295. attributes:
  1296. id -- ID
  1297. ref -- QName, required
  1298. use -- ('optional' | 'prohibited' | 'required'), optional
  1299. default -- string
  1300. fixed -- string
  1301. contents:
  1302. annotation?
  1303. """
  1304. required = ['ref']
  1305. attributes = {'id':None,
  1306. 'ref':None,
  1307. 'use':'optional',
  1308. 'default':None,
  1309. 'fixed':None}
  1310. contents = {'xsd':['annotation']}
  1311. tag = 'attribute'
  1312. def __init__(self, parent):
  1313. XMLSchemaComponent.__init__(self, parent)
  1314. self.annotation = None
  1315. def getAttributeDeclaration(self, attribute='ref'):
  1316. return XMLSchemaComponent.getAttributeDeclaration(self, attribute)
  1317. def fromDom(self, node):
  1318. self.setAttributes(node)
  1319. contents = self.getContents(node)
  1320. for i in contents:
  1321. component = SplitQName(i.getTagName())[1]
  1322. if component == 'annotation' and not self.annotation:
  1323. self.annotation = Annotation(self)
  1324. self.annotation.fromDom(i)
  1325. else:
  1326. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1327. class AttributeGroupDefinition(XMLSchemaComponent,\
  1328. AttributeGroupMarker,\
  1329. DefinitionMarker):
  1330. """<attributeGroup name>
  1331. parents:
  1332. schema, redefine
  1333. attributes:
  1334. id -- ID
  1335. name -- NCName, required
  1336. contents:
  1337. annotation?, (attribute | attributeGroup)*, anyAttribute?
  1338. """
  1339. required = ['name']
  1340. attributes = {'id':None,
  1341. 'name':None}
  1342. contents = {'xsd':['annotation', 'attribute', 'attributeGroup', 'anyAttribute']}
  1343. tag = 'attributeGroup'
  1344. def __init__(self, parent):
  1345. XMLSchemaComponent.__init__(self, parent)
  1346. self.annotation = None
  1347. self.attr_content = None
  1348. def getAttributeContent(self):
  1349. return self.attr_content
  1350. def fromDom(self, node):
  1351. self.setAttributes(node)
  1352. contents = self.getContents(node)
  1353. content = []
  1354. for indx in range(len(contents)):
  1355. component = SplitQName(contents[indx].getTagName())[1]
  1356. if (component == 'annotation') and (not indx):
  1357. self.annotation = Annotation(self)
  1358. self.annotation.fromDom(contents[indx])
  1359. elif component == 'attribute':
  1360. if contents[indx].hasattr('name'):
  1361. content.append(LocalAttributeDeclaration(self))
  1362. elif contents[indx].hasattr('ref'):
  1363. content.append(AttributeReference(self))
  1364. else:
  1365. raise SchemaError, 'Unknown attribute type'
  1366. content[-1].fromDom(contents[indx])
  1367. elif component == 'attributeGroup':
  1368. content.append(AttributeGroupReference(self))
  1369. content[-1].fromDom(contents[indx])
  1370. elif component == 'anyAttribute':
  1371. if len(contents) != indx+1:
  1372. raise SchemaError, 'anyAttribute is out of order in %s' %self.getItemTrace()
  1373. content.append(AttributeWildCard(self))
  1374. content[-1].fromDom(contents[indx])
  1375. else:
  1376. raise SchemaError, 'Unknown component (%s)' %(contents[indx].getTagName())
  1377. self.attr_content = tuple(content)
  1378. class AttributeGroupReference(XMLSchemaComponent,\
  1379. AttributeGroupMarker,\
  1380. ReferenceMarker):
  1381. """<attributeGroup ref>
  1382. parents:
  1383. complexType, restriction, extension, attributeGroup
  1384. attributes:
  1385. id -- ID
  1386. ref -- QName, required
  1387. contents:
  1388. annotation?
  1389. """
  1390. required = ['ref']
  1391. attributes = {'id':None,
  1392. 'ref':None}
  1393. contents = {'xsd':['annotation']}
  1394. tag = 'attributeGroup'
  1395. def __init__(self, parent):
  1396. XMLSchemaComponent.__init__(self, parent)
  1397. self.annotation = None
  1398. def getAttributeGroup(self, attribute='ref'):
  1399. """attribute -- attribute with a QName value (eg. type).
  1400. collection -- check types collection in parent Schema instance
  1401. """
  1402. return XMLSchemaComponent.getAttributeGroup(self, attribute)
  1403. def fromDom(self, node):
  1404. self.setAttributes(node)
  1405. contents = self.getContents(node)
  1406. for i in contents:
  1407. component = SplitQName(i.getTagName())[1]
  1408. if component == 'annotation' and not self.annotation:
  1409. self.annotation = Annotation(self)
  1410. self.annotation.fromDom(i)
  1411. else:
  1412. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1413. ######################################################
  1414. # Elements
  1415. #####################################################
  1416. class IdentityConstrants(XMLSchemaComponent):
  1417. """Allow one to uniquely identify nodes in a document and ensure the
  1418. integrity of references between them.
  1419. attributes -- dictionary of attributes
  1420. selector -- XPath to selected nodes
  1421. fields -- list of XPath to key field
  1422. """
  1423. def __init__(self, parent):
  1424. XMLSchemaComponent.__init__(self, parent)
  1425. self.selector = None
  1426. self.fields = None
  1427. self.annotation = None
  1428. def fromDom(self, node):
  1429. self.setAttributes(node)
  1430. contents = self.getContents(node)
  1431. fields = []
  1432. for i in contents:
  1433. component = SplitQName(i.getTagName())[1]
  1434. if component in self.__class__.contents['xsd']:
  1435. if component == 'annotation' and not self.annotation:
  1436. self.annotation = Annotation(self)
  1437. self.annotation.fromDom(i)
  1438. elif component == 'selector':
  1439. self.selector = self.Selector(self)
  1440. self.selector.fromDom(i)
  1441. continue
  1442. elif component == 'field':
  1443. fields.append(self.Field(self))
  1444. fields[-1].fromDom(i)
  1445. continue
  1446. else:
  1447. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1448. else:
  1449. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1450. self.fields = tuple(fields)
  1451. class Constraint(XMLSchemaComponent):
  1452. def __init__(self, parent):
  1453. XMLSchemaComponent.__init__(self, parent)
  1454. self.annotation = None
  1455. def fromDom(self, node):
  1456. self.setAttributes(node)
  1457. contents = self.getContents(node)
  1458. for i in contents:
  1459. component = SplitQName(i.getTagName())[1]
  1460. if component in self.__class__.contents['xsd']:
  1461. if component == 'annotation' and not self.annotation:
  1462. self.annotation = Annotation(self)
  1463. self.annotation.fromDom(i)
  1464. else:
  1465. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1466. else:
  1467. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1468. class Selector(Constraint):
  1469. """<selector xpath>
  1470. parent:
  1471. unique, key, keyref
  1472. attributes:
  1473. id -- ID
  1474. xpath -- XPath subset, required
  1475. contents:
  1476. annotation?
  1477. """
  1478. required = ['xpath']
  1479. attributes = {'id':None,
  1480. 'xpath':None}
  1481. contents = {'xsd':['annotation']}
  1482. tag = 'selector'
  1483. class Field(Constraint):
  1484. """<field xpath>
  1485. parent:
  1486. unique, key, keyref
  1487. attributes:
  1488. id -- ID
  1489. xpath -- XPath subset, required
  1490. contents:
  1491. annotation?
  1492. """
  1493. required = ['xpath']
  1494. attributes = {'id':None,
  1495. 'xpath':None}
  1496. contents = {'xsd':['annotation']}
  1497. tag = 'field'
  1498. class Unique(IdentityConstrants):
  1499. """<unique name> Enforce fields are unique w/i a specified scope.
  1500. parent:
  1501. element
  1502. attributes:
  1503. id -- ID
  1504. name -- NCName, required
  1505. contents:
  1506. annotation?, selector, field+
  1507. """
  1508. required = ['name']
  1509. attributes = {'id':None,
  1510. 'name':None}
  1511. contents = {'xsd':['annotation', 'selector', 'field']}
  1512. tag = 'unique'
  1513. class Key(IdentityConstrants):
  1514. """<key name> Enforce fields are unique w/i a specified scope, and all
  1515. field values are present w/i document. Fields cannot
  1516. be nillable.
  1517. parent:
  1518. element
  1519. attributes:
  1520. id -- ID
  1521. name -- NCName, required
  1522. contents:
  1523. annotation?, selector, field+
  1524. """
  1525. required = ['name']
  1526. attributes = {'id':None,
  1527. 'name':None}
  1528. contents = {'xsd':['annotation', 'selector', 'field']}
  1529. tag = 'key'
  1530. class KeyRef(IdentityConstrants):
  1531. """<keyref name refer> Ensure a match between two sets of values in an
  1532. instance.
  1533. parent:
  1534. element
  1535. attributes:
  1536. id -- ID
  1537. name -- NCName, required
  1538. refer -- QName, required
  1539. contents:
  1540. annotation?, selector, field+
  1541. """
  1542. required = ['name', 'refer']
  1543. attributes = {'id':None,
  1544. 'name':None,
  1545. 'refer':None}
  1546. contents = {'xsd':['annotation', 'selector', 'field']}
  1547. tag = 'keyref'
  1548. class ElementDeclaration(XMLSchemaComponent,\
  1549. ElementMarker,\
  1550. DeclarationMarker):
  1551. """<element name>
  1552. parents:
  1553. schema
  1554. attributes:
  1555. id -- ID
  1556. name -- NCName, required
  1557. type -- QName
  1558. default -- string
  1559. fixed -- string
  1560. nillable -- boolean, false
  1561. abstract -- boolean, false
  1562. substitutionGroup -- QName
  1563. block -- ('#all' | ('substition' | 'extension' | 'restriction')*),
  1564. schema.blockDefault
  1565. final -- ('#all' | ('extension' | 'restriction')*),
  1566. schema.finalDefault
  1567. contents:
  1568. annotation?, (simpleType,complexType)?, (key | keyref | unique)*
  1569. """
  1570. required = ['name']
  1571. attributes = {'id':None,
  1572. 'name':None,
  1573. 'type':None,
  1574. 'default':None,
  1575. 'fixed':None,
  1576. 'nillable':0,
  1577. 'abstract':0,
  1578. 'substitutionGroup':None,
  1579. 'block':lambda self: self._parent().getBlockDefault(),
  1580. 'final':lambda self: self._parent().getFinalDefault()}
  1581. contents = {'xsd':['annotation', 'simpleType', 'complexType', 'key',\
  1582. 'keyref', 'unique']}
  1583. tag = 'element'
  1584. def __init__(self, parent):
  1585. XMLSchemaComponent.__init__(self, parent)
  1586. self.annotation = None
  1587. self.content = None
  1588. self.constraints = ()
  1589. def isQualified(self):
  1590. """
  1591. Global elements are always qualified.
  1592. """
  1593. return True
  1594. def getElementDeclaration(self, attribute):
  1595. raise Warning, 'invalid operation for <%s>' %self.tag
  1596. def getTypeDefinition(self, attribute=None):
  1597. """
  1598. If attribute is None, "type" is assumed, return the corresponding
  1599. representation of the global type definition (TypeDefinition),
  1600. or the local definition if don't find "type". To maintain backwards
  1601. compat, if attribute is provided call base class method.
  1602. """
  1603. if attribute:
  1604. return XMLSchemaComponent.getTypeDefinition(self, attribute)
  1605. gt = XMLSchemaComponent.getTypeDefinition(self, 'type')
  1606. if gt:
  1607. return gt
  1608. return self.content
  1609. def getConstraints(self):
  1610. return self._constraints
  1611. def setConstraints(self, constraints):
  1612. self._constraints = tuple(constraints)
  1613. constraints = property(getConstraints, setConstraints, None, "tuple of key, keyref, unique constraints")
  1614. def fromDom(self, node):
  1615. self.setAttributes(node)
  1616. contents = self.getContents(node)
  1617. constraints = []
  1618. for i in contents:
  1619. component = SplitQName(i.getTagName())[1]
  1620. if component in self.__class__.contents['xsd']:
  1621. if component == 'annotation' and not self.annotation:
  1622. self.annotation = Annotation(self)
  1623. self.annotation.fromDom(i)
  1624. elif component == 'simpleType' and not self.content:
  1625. self.content = AnonymousSimpleType(self)
  1626. self.content.fromDom(i)
  1627. elif component == 'complexType' and not self.content:
  1628. self.content = LocalComplexType(self)
  1629. self.content.fromDom(i)
  1630. elif component == 'key':
  1631. constraints.append(Key(self))
  1632. constraints[-1].fromDom(i)
  1633. elif component == 'keyref':
  1634. constraints.append(KeyRef(self))
  1635. constraints[-1].fromDom(i)
  1636. elif component == 'unique':
  1637. constraints.append(Unique(self))
  1638. constraints[-1].fromDom(i)
  1639. else:
  1640. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1641. else:
  1642. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1643. self.constraints = constraints
  1644. class LocalElementDeclaration(ElementDeclaration,\
  1645. LocalMarker):
  1646. """<element>
  1647. parents:
  1648. all, choice, sequence
  1649. attributes:
  1650. id -- ID
  1651. name -- NCName, required
  1652. form -- ('qualified' | 'unqualified'), schema.elementFormDefault
  1653. type -- QName
  1654. minOccurs -- Whole Number, 1
  1655. maxOccurs -- (Whole Number | 'unbounded'), 1
  1656. default -- string
  1657. fixed -- string
  1658. nillable -- boolean, false
  1659. block -- ('#all' | ('extension' | 'restriction')*), schema.blockDefault
  1660. contents:
  1661. annotation?, (simpleType,complexType)?, (key | keyref | unique)*
  1662. """
  1663. required = ['name']
  1664. attributes = {'id':None,
  1665. 'name':None,
  1666. 'form':lambda self: GetSchema(self).getElementFormDefault(),
  1667. 'type':None,
  1668. 'minOccurs':'1',
  1669. 'maxOccurs':'1',
  1670. 'default':None,
  1671. 'fixed':None,
  1672. 'nillable':0,
  1673. 'abstract':0,
  1674. 'block':lambda self: GetSchema(self).getBlockDefault()}
  1675. contents = {'xsd':['annotation', 'simpleType', 'complexType', 'key',\
  1676. 'keyref', 'unique']}
  1677. def isQualified(self):
  1678. """
  1679. Local elements can be qualified or unqualifed according
  1680. to the attribute form, or the elementFormDefault. By default
  1681. local elements are unqualified.
  1682. """
  1683. form = self.getAttribute('form')
  1684. if form == 'qualified':
  1685. return True
  1686. if form == 'unqualified':
  1687. return False
  1688. raise SchemaError, 'Bad form (%s) for element: %s' %(form, self.getItemTrace())
  1689. class ElementReference(XMLSchemaComponent,\
  1690. ElementMarker,\
  1691. ReferenceMarker):
  1692. """<element ref>
  1693. parents:
  1694. all, choice, sequence
  1695. attributes:
  1696. id -- ID
  1697. ref -- QName, required
  1698. minOccurs -- Whole Number, 1
  1699. maxOccurs -- (Whole Number | 'unbounded'), 1
  1700. contents:
  1701. annotation?
  1702. """
  1703. required = ['ref']
  1704. attributes = {'id':None,
  1705. 'ref':None,
  1706. 'minOccurs':'1',
  1707. 'maxOccurs':'1'}
  1708. contents = {'xsd':['annotation']}
  1709. tag = 'element'
  1710. def __init__(self, parent):
  1711. XMLSchemaComponent.__init__(self, parent)
  1712. self.annotation = None
  1713. def getElementDeclaration(self, attribute=None):
  1714. """If attribute is None, "ref" is assumed, return the corresponding
  1715. representation of the global element declaration (ElementDeclaration),
  1716. To maintain backwards compat, if attribute is provided call base class method.
  1717. """
  1718. if attribute:
  1719. return XMLSchemaComponent.getElementDeclaration(self, attribute)
  1720. return XMLSchemaComponent.getElementDeclaration(self, 'ref')
  1721. def fromDom(self, node):
  1722. self.annotation = None
  1723. self.setAttributes(node)
  1724. for i in self.getContents(node):
  1725. component = SplitQName(i.getTagName())[1]
  1726. if component in self.__class__.contents['xsd']:
  1727. if component == 'annotation' and not self.annotation:
  1728. self.annotation = Annotation(self)
  1729. self.annotation.fromDom(i)
  1730. else:
  1731. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1732. class ElementWildCard(LocalElementDeclaration, WildCardMarker):
  1733. """<any>
  1734. parents:
  1735. choice, sequence
  1736. attributes:
  1737. id -- ID
  1738. minOccurs -- Whole Number, 1
  1739. maxOccurs -- (Whole Number | 'unbounded'), 1
  1740. namespace -- '##any' | '##other' |
  1741. (anyURI* | '##targetNamespace' | '##local'), ##any
  1742. processContents -- 'lax' | 'skip' | 'strict', strict
  1743. contents:
  1744. annotation?
  1745. """
  1746. required = []
  1747. attributes = {'id':None,
  1748. 'minOccurs':'1',
  1749. 'maxOccurs':'1',
  1750. 'namespace':'##any',
  1751. 'processContents':'strict'}
  1752. contents = {'xsd':['annotation']}
  1753. tag = 'any'
  1754. def __init__(self, parent):
  1755. XMLSchemaComponent.__init__(self, parent)
  1756. self.annotation = None
  1757. def isQualified(self):
  1758. """
  1759. Global elements are always qualified, but if processContents
  1760. are not strict could have dynamically generated local elements.
  1761. """
  1762. return GetSchema(self).isElementFormDefaultQualified()
  1763. def getTypeDefinition(self, attribute):
  1764. raise Warning, 'invalid operation for <%s>' % self.tag
  1765. def fromDom(self, node):
  1766. self.annotation = None
  1767. self.setAttributes(node)
  1768. for i in self.getContents(node):
  1769. component = SplitQName(i.getTagName())[1]
  1770. if component in self.__class__.contents['xsd']:
  1771. if component == 'annotation' and not self.annotation:
  1772. self.annotation = Annotation(self)
  1773. self.annotation.fromDom(i)
  1774. else:
  1775. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1776. ######################################################
  1777. # Model Groups
  1778. #####################################################
  1779. class Sequence(XMLSchemaComponent,\
  1780. SequenceMarker):
  1781. """<sequence>
  1782. parents:
  1783. complexType, extension, restriction, group, choice, sequence
  1784. attributes:
  1785. id -- ID
  1786. minOccurs -- Whole Number, 1
  1787. maxOccurs -- (Whole Number | 'unbounded'), 1
  1788. contents:
  1789. annotation?, (element | group | choice | sequence | any)*
  1790. """
  1791. attributes = {'id':None,
  1792. 'minOccurs':'1',
  1793. 'maxOccurs':'1'}
  1794. contents = {'xsd':['annotation', 'element', 'group', 'choice', 'sequence',\
  1795. 'any']}
  1796. tag = 'sequence'
  1797. def __init__(self, parent):
  1798. XMLSchemaComponent.__init__(self, parent)
  1799. self.annotation = None
  1800. self.content = None
  1801. def fromDom(self, node):
  1802. self.setAttributes(node)
  1803. contents = self.getContents(node)
  1804. content = []
  1805. for i in contents:
  1806. component = SplitQName(i.getTagName())[1]
  1807. if component in self.__class__.contents['xsd']:
  1808. if component == 'annotation' and not self.annotation:
  1809. self.annotation = Annotation(self)
  1810. self.annotation.fromDom(i)
  1811. continue
  1812. elif component == 'element':
  1813. if i.hasattr('ref'):
  1814. content.append(ElementReference(self))
  1815. else:
  1816. content.append(LocalElementDeclaration(self))
  1817. elif component == 'group':
  1818. content.append(ModelGroupReference(self))
  1819. elif component == 'choice':
  1820. content.append(Choice(self))
  1821. elif component == 'sequence':
  1822. content.append(Sequence(self))
  1823. elif component == 'any':
  1824. content.append(ElementWildCard(self))
  1825. else:
  1826. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1827. content[-1].fromDom(i)
  1828. else:
  1829. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1830. self.content = tuple(content)
  1831. class All(XMLSchemaComponent,\
  1832. AllMarker):
  1833. """<all>
  1834. parents:
  1835. complexType, extension, restriction, group
  1836. attributes:
  1837. id -- ID
  1838. minOccurs -- '0' | '1', 1
  1839. maxOccurs -- '1', 1
  1840. contents:
  1841. annotation?, element*
  1842. """
  1843. attributes = {'id':None,
  1844. 'minOccurs':'1',
  1845. 'maxOccurs':'1'}
  1846. contents = {'xsd':['annotation', 'element']}
  1847. tag = 'all'
  1848. def __init__(self, parent):
  1849. XMLSchemaComponent.__init__(self, parent)
  1850. self.annotation = None
  1851. self.content = None
  1852. def fromDom(self, node):
  1853. self.setAttributes(node)
  1854. contents = self.getContents(node)
  1855. content = []
  1856. for i in contents:
  1857. component = SplitQName(i.getTagName())[1]
  1858. if component in self.__class__.contents['xsd']:
  1859. if component == 'annotation' and not self.annotation:
  1860. self.annotation = Annotation(self)
  1861. self.annotation.fromDom(i)
  1862. continue
  1863. elif component == 'element':
  1864. if i.hasattr('ref'):
  1865. content.append(ElementReference(self))
  1866. else:
  1867. content.append(LocalElementDeclaration(self))
  1868. else:
  1869. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1870. content[-1].fromDom(i)
  1871. else:
  1872. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1873. self.content = tuple(content)
  1874. class Choice(XMLSchemaComponent,\
  1875. ChoiceMarker):
  1876. """<choice>
  1877. parents:
  1878. complexType, extension, restriction, group, choice, sequence
  1879. attributes:
  1880. id -- ID
  1881. minOccurs -- Whole Number, 1
  1882. maxOccurs -- (Whole Number | 'unbounded'), 1
  1883. contents:
  1884. annotation?, (element | group | choice | sequence | any)*
  1885. """
  1886. attributes = {'id':None,
  1887. 'minOccurs':'1',
  1888. 'maxOccurs':'1'}
  1889. contents = {'xsd':['annotation', 'element', 'group', 'choice', 'sequence',\
  1890. 'any']}
  1891. tag = 'choice'
  1892. def __init__(self, parent):
  1893. XMLSchemaComponent.__init__(self, parent)
  1894. self.annotation = None
  1895. self.content = None
  1896. def fromDom(self, node):
  1897. self.setAttributes(node)
  1898. contents = self.getContents(node)
  1899. content = []
  1900. for i in contents:
  1901. component = SplitQName(i.getTagName())[1]
  1902. if component in self.__class__.contents['xsd']:
  1903. if component == 'annotation' and not self.annotation:
  1904. self.annotation = Annotation(self)
  1905. self.annotation.fromDom(i)
  1906. continue
  1907. elif component == 'element':
  1908. if i.hasattr('ref'):
  1909. content.append(ElementReference(self))
  1910. else:
  1911. content.append(LocalElementDeclaration(self))
  1912. elif component == 'group':
  1913. content.append(ModelGroupReference(self))
  1914. elif component == 'choice':
  1915. content.append(Choice(self))
  1916. elif component == 'sequence':
  1917. content.append(Sequence(self))
  1918. elif component == 'any':
  1919. content.append(ElementWildCard(self))
  1920. else:
  1921. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1922. content[-1].fromDom(i)
  1923. else:
  1924. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1925. self.content = tuple(content)
  1926. class ModelGroupDefinition(XMLSchemaComponent,\
  1927. ModelGroupMarker,\
  1928. DefinitionMarker):
  1929. """<group name>
  1930. parents:
  1931. redefine, schema
  1932. attributes:
  1933. id -- ID
  1934. name -- NCName, required
  1935. contents:
  1936. annotation?, (all | choice | sequence)?
  1937. """
  1938. required = ['name']
  1939. attributes = {'id':None,
  1940. 'name':None}
  1941. contents = {'xsd':['annotation', 'all', 'choice', 'sequence']}
  1942. tag = 'group'
  1943. def __init__(self, parent):
  1944. XMLSchemaComponent.__init__(self, parent)
  1945. self.annotation = None
  1946. self.content = None
  1947. def fromDom(self, node):
  1948. self.setAttributes(node)
  1949. contents = self.getContents(node)
  1950. for i in contents:
  1951. component = SplitQName(i.getTagName())[1]
  1952. if component in self.__class__.contents['xsd']:
  1953. if component == 'annotation' and not self.annotation:
  1954. self.annotation = Annotation(self)
  1955. self.annotation.fromDom(i)
  1956. continue
  1957. elif component == 'all' and not self.content:
  1958. self.content = All(self)
  1959. elif component == 'choice' and not self.content:
  1960. self.content = Choice(self)
  1961. elif component == 'sequence' and not self.content:
  1962. self.content = Sequence(self)
  1963. else:
  1964. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1965. self.content.fromDom(i)
  1966. else:
  1967. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  1968. class ModelGroupReference(XMLSchemaComponent,\
  1969. ModelGroupMarker,\
  1970. ReferenceMarker):
  1971. """<group ref>
  1972. parents:
  1973. choice, complexType, extension, restriction, sequence
  1974. attributes:
  1975. id -- ID
  1976. ref -- NCName, required
  1977. minOccurs -- Whole Number, 1
  1978. maxOccurs -- (Whole Number | 'unbounded'), 1
  1979. contents:
  1980. annotation?
  1981. """
  1982. required = ['ref']
  1983. attributes = {'id':None,
  1984. 'ref':None,
  1985. 'minOccurs':'1',
  1986. 'maxOccurs':'1'}
  1987. contents = {'xsd':['annotation']}
  1988. tag = 'group'
  1989. def __init__(self, parent):
  1990. XMLSchemaComponent.__init__(self, parent)
  1991. self.annotation = None
  1992. def getModelGroupReference(self):
  1993. return self.getModelGroup('ref')
  1994. def fromDom(self, node):
  1995. self.setAttributes(node)
  1996. contents = self.getContents(node)
  1997. for i in contents:
  1998. component = SplitQName(i.getTagName())[1]
  1999. if component in self.__class__.contents['xsd']:
  2000. if component == 'annotation' and not self.annotation:
  2001. self.annotation = Annotation(self)
  2002. self.annotation.fromDom(i)
  2003. else:
  2004. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  2005. else:
  2006. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  2007. class ComplexType(XMLSchemaComponent,\
  2008. DefinitionMarker,\
  2009. ComplexMarker):
  2010. """<complexType name>
  2011. parents:
  2012. redefine, schema
  2013. attributes:
  2014. id -- ID
  2015. name -- NCName, required
  2016. mixed -- boolean, false
  2017. abstract -- boolean, false
  2018. block -- ('#all' | ('extension' | 'restriction')*), schema.blockDefault
  2019. final -- ('#all' | ('extension' | 'restriction')*), schema.finalDefault
  2020. contents:
  2021. annotation?, (simpleContent | complexContent |
  2022. ((group | all | choice | sequence)?, (attribute | attributeGroup)*, anyAttribute?))
  2023. """
  2024. required = ['name']
  2025. attributes = {'id':None,
  2026. 'name':None,
  2027. 'mixed':0,
  2028. 'abstract':0,
  2029. 'block':lambda self: self._parent().getBlockDefault(),
  2030. 'final':lambda self: self._parent().getFinalDefault()}
  2031. contents = {'xsd':['annotation', 'simpleContent', 'complexContent',\
  2032. 'group', 'all', 'choice', 'sequence', 'attribute', 'attributeGroup',\
  2033. 'anyAttribute', 'any']}
  2034. tag = 'complexType'
  2035. def __init__(self, parent):
  2036. XMLSchemaComponent.__init__(self, parent)
  2037. self.annotation = None
  2038. self.content = None
  2039. self.attr_content = None
  2040. def isMixed(self):
  2041. m = self.getAttribute('mixed')
  2042. if m == 0 or m == False:
  2043. return False
  2044. if isinstance(m, basestring) is True:
  2045. if m in ('false', '0'):
  2046. return False
  2047. if m in ('true', '1'):
  2048. return True
  2049. raise SchemaError, 'invalid value for attribute mixed(%s): %s'\
  2050. %(m, self.getItemTrace())
  2051. def getAttributeContent(self):
  2052. return self.attr_content
  2053. def getElementDeclaration(self, attribute):
  2054. raise Warning, 'invalid operation for <%s>' %self.tag
  2055. def getTypeDefinition(self, attribute):
  2056. raise Warning, 'invalid operation for <%s>' %self.tag
  2057. def fromDom(self, node):
  2058. self.setAttributes(node)
  2059. contents = self.getContents(node)
  2060. indx = 0
  2061. num = len(contents)
  2062. if not num:
  2063. return
  2064. component = SplitQName(contents[indx].getTagName())[1]
  2065. if component == 'annotation':
  2066. self.annotation = Annotation(self)
  2067. self.annotation.fromDom(contents[indx])
  2068. indx += 1
  2069. component = SplitQName(contents[indx].getTagName())[1]
  2070. self.content = None
  2071. if component == 'simpleContent':
  2072. self.content = self.__class__.SimpleContent(self)
  2073. self.content.fromDom(contents[indx])
  2074. elif component == 'complexContent':
  2075. self.content = self.__class__.ComplexContent(self)
  2076. self.content.fromDom(contents[indx])
  2077. else:
  2078. if component == 'all':
  2079. self.content = All(self)
  2080. elif component == 'choice':
  2081. self.content = Choice(self)
  2082. elif component == 'sequence':
  2083. self.content = Sequence(self)
  2084. elif component == 'group':
  2085. self.content = ModelGroupReference(self)
  2086. if self.content:
  2087. self.content.fromDom(contents[indx])
  2088. indx += 1
  2089. self.attr_content = []
  2090. while indx < num:
  2091. component = SplitQName(contents[indx].getTagName())[1]
  2092. if component == 'attribute':
  2093. if contents[indx].hasattr('ref'):
  2094. self.attr_content.append(AttributeReference(self))
  2095. else:
  2096. self.attr_content.append(LocalAttributeDeclaration(self))
  2097. elif component == 'attributeGroup':
  2098. self.attr_content.append(AttributeGroupReference(self))
  2099. elif component == 'anyAttribute':
  2100. self.attr_content.append(AttributeWildCard(self))
  2101. else:
  2102. raise SchemaError, 'Unknown component (%s): %s' \
  2103. %(contents[indx].getTagName(),self.getItemTrace())
  2104. self.attr_content[-1].fromDom(contents[indx])
  2105. indx += 1
  2106. class _DerivedType(XMLSchemaComponent):
  2107. def __init__(self, parent):
  2108. XMLSchemaComponent.__init__(self, parent)
  2109. self.annotation = None
  2110. # XXX remove attribute derivation, inconsistent
  2111. self.derivation = None
  2112. self.content = None
  2113. def fromDom(self, node):
  2114. self.setAttributes(node)
  2115. contents = self.getContents(node)
  2116. for i in contents:
  2117. component = SplitQName(i.getTagName())[1]
  2118. if component in self.__class__.contents['xsd']:
  2119. if component == 'annotation' and not self.annotation:
  2120. self.annotation = Annotation(self)
  2121. self.annotation.fromDom(i)
  2122. continue
  2123. elif component == 'restriction' and not self.derivation:
  2124. self.derivation = self.__class__.Restriction(self)
  2125. elif component == 'extension' and not self.derivation:
  2126. self.derivation = self.__class__.Extension(self)
  2127. else:
  2128. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  2129. else:
  2130. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  2131. self.derivation.fromDom(i)
  2132. self.content = self.derivation
  2133. class ComplexContent(_DerivedType,\
  2134. ComplexMarker):
  2135. """<complexContent>
  2136. parents:
  2137. complexType
  2138. attributes:
  2139. id -- ID
  2140. mixed -- boolean, false
  2141. contents:
  2142. annotation?, (restriction | extension)
  2143. """
  2144. attributes = {'id':None,
  2145. 'mixed':0}
  2146. contents = {'xsd':['annotation', 'restriction', 'extension']}
  2147. tag = 'complexContent'
  2148. def isMixed(self):
  2149. m = self.getAttribute('mixed')
  2150. if m == 0 or m == False:
  2151. return False
  2152. if isinstance(m, basestring) is True:
  2153. if m in ('false', '0'):
  2154. return False
  2155. if m in ('true', '1'):
  2156. return True
  2157. raise SchemaError, 'invalid value for attribute mixed(%s): %s'\
  2158. %(m, self.getItemTrace())
  2159. class _DerivationBase(XMLSchemaComponent):
  2160. """<extension>,<restriction>
  2161. parents:
  2162. complexContent
  2163. attributes:
  2164. id -- ID
  2165. base -- QName, required
  2166. contents:
  2167. annotation?, (group | all | choice | sequence)?,
  2168. (attribute | attributeGroup)*, anyAttribute?
  2169. """
  2170. required = ['base']
  2171. attributes = {'id':None,
  2172. 'base':None }
  2173. contents = {'xsd':['annotation', 'group', 'all', 'choice',\
  2174. 'sequence', 'attribute', 'attributeGroup', 'anyAttribute']}
  2175. def __init__(self, parent):
  2176. XMLSchemaComponent.__init__(self, parent)
  2177. self.annotation = None
  2178. self.content = None
  2179. self.attr_content = None
  2180. def getAttributeContent(self):
  2181. return self.attr_content
  2182. def fromDom(self, node):
  2183. self.setAttributes(node)
  2184. contents = self.getContents(node)
  2185. indx = 0
  2186. num = len(contents)
  2187. #XXX ugly
  2188. if not num:
  2189. return
  2190. component = SplitQName(contents[indx].getTagName())[1]
  2191. if component == 'annotation':
  2192. self.annotation = Annotation(self)
  2193. self.annotation.fromDom(contents[indx])
  2194. indx += 1
  2195. component = SplitQName(contents[indx].getTagName())[1]
  2196. if component == 'all':
  2197. self.content = All(self)
  2198. self.content.fromDom(contents[indx])
  2199. indx += 1
  2200. elif component == 'choice':
  2201. self.content = Choice(self)
  2202. self.content.fromDom(contents[indx])
  2203. indx += 1
  2204. elif component == 'sequence':
  2205. self.content = Sequence(self)
  2206. self.content.fromDom(contents[indx])
  2207. indx += 1
  2208. elif component == 'group':
  2209. self.content = ModelGroupReference(self)
  2210. self.content.fromDom(contents[indx])
  2211. indx += 1
  2212. else:
  2213. self.content = None
  2214. self.attr_content = []
  2215. while indx < num:
  2216. component = SplitQName(contents[indx].getTagName())[1]
  2217. if component == 'attribute':
  2218. if contents[indx].hasattr('ref'):
  2219. self.attr_content.append(AttributeReference(self))
  2220. else:
  2221. self.attr_content.append(LocalAttributeDeclaration(self))
  2222. elif component == 'attributeGroup':
  2223. if contents[indx].hasattr('ref'):
  2224. self.attr_content.append(AttributeGroupReference(self))
  2225. else:
  2226. self.attr_content.append(AttributeGroupDefinition(self))
  2227. elif component == 'anyAttribute':
  2228. self.attr_content.append(AttributeWildCard(self))
  2229. else:
  2230. raise SchemaError, 'Unknown component (%s)' %(contents[indx].getTagName())
  2231. self.attr_content[-1].fromDom(contents[indx])
  2232. indx += 1
  2233. class Extension(_DerivationBase,
  2234. ExtensionMarker):
  2235. """<extension base>
  2236. parents:
  2237. complexContent
  2238. attributes:
  2239. id -- ID
  2240. base -- QName, required
  2241. contents:
  2242. annotation?, (group | all | choice | sequence)?,
  2243. (attribute | attributeGroup)*, anyAttribute?
  2244. """
  2245. tag = 'extension'
  2246. class Restriction(_DerivationBase,\
  2247. RestrictionMarker):
  2248. """<restriction base>
  2249. parents:
  2250. complexContent
  2251. attributes:
  2252. id -- ID
  2253. base -- QName, required
  2254. contents:
  2255. annotation?, (group | all | choice | sequence)?,
  2256. (attribute | attributeGroup)*, anyAttribute?
  2257. """
  2258. tag = 'restriction'
  2259. class SimpleContent(_DerivedType,\
  2260. SimpleMarker):
  2261. """<simpleContent>
  2262. parents:
  2263. complexType
  2264. attributes:
  2265. id -- ID
  2266. contents:
  2267. annotation?, (restriction | extension)
  2268. """
  2269. attributes = {'id':None}
  2270. contents = {'xsd':['annotation', 'restriction', 'extension']}
  2271. tag = 'simpleContent'
  2272. class Extension(XMLSchemaComponent,\
  2273. ExtensionMarker):
  2274. """<extension base>
  2275. parents:
  2276. simpleContent
  2277. attributes:
  2278. id -- ID
  2279. base -- QName, required
  2280. contents:
  2281. annotation?, (attribute | attributeGroup)*, anyAttribute?
  2282. """
  2283. required = ['base']
  2284. attributes = {'id':None,
  2285. 'base':None }
  2286. contents = {'xsd':['annotation', 'attribute', 'attributeGroup',
  2287. 'anyAttribute']}
  2288. tag = 'extension'
  2289. def __init__(self, parent):
  2290. XMLSchemaComponent.__init__(self, parent)
  2291. self.annotation = None
  2292. self.attr_content = None
  2293. def getAttributeContent(self):
  2294. return self.attr_content
  2295. def fromDom(self, node):
  2296. self.setAttributes(node)
  2297. contents = self.getContents(node)
  2298. indx = 0
  2299. num = len(contents)
  2300. if num:
  2301. component = SplitQName(contents[indx].getTagName())[1]
  2302. if component == 'annotation':
  2303. self.annotation = Annotation(self)
  2304. self.annotation.fromDom(contents[indx])
  2305. indx += 1
  2306. component = SplitQName(contents[indx].getTagName())[1]
  2307. content = []
  2308. while indx < num:
  2309. component = SplitQName(contents[indx].getTagName())[1]
  2310. if component == 'attribute':
  2311. if contents[indx].hasattr('ref'):
  2312. content.append(AttributeReference(self))
  2313. else:
  2314. content.append(LocalAttributeDeclaration(self))
  2315. elif component == 'attributeGroup':
  2316. content.append(AttributeGroupReference(self))
  2317. elif component == 'anyAttribute':
  2318. content.append(AttributeWildCard(self))
  2319. else:
  2320. raise SchemaError, 'Unknown component (%s)'\
  2321. %(contents[indx].getTagName())
  2322. content[-1].fromDom(contents[indx])
  2323. indx += 1
  2324. self.attr_content = tuple(content)
  2325. class Restriction(XMLSchemaComponent,\
  2326. RestrictionMarker):
  2327. """<restriction base>
  2328. parents:
  2329. simpleContent
  2330. attributes:
  2331. id -- ID
  2332. base -- QName, required
  2333. contents:
  2334. annotation?, simpleType?, (enumeration | length |
  2335. maxExclusive | maxInclusive | maxLength | minExclusive |
  2336. minInclusive | minLength | pattern | fractionDigits |
  2337. totalDigits | whiteSpace)*, (attribute | attributeGroup)*,
  2338. anyAttribute?
  2339. """
  2340. required = ['base']
  2341. attributes = {'id':None,
  2342. 'base':None }
  2343. contents = {'xsd':['annotation', 'simpleType', 'attribute',\
  2344. 'attributeGroup', 'anyAttribute'] + RestrictionMarker.facets}
  2345. tag = 'restriction'
  2346. def __init__(self, parent):
  2347. XMLSchemaComponent.__init__(self, parent)
  2348. self.annotation = None
  2349. self.content = None
  2350. self.attr_content = None
  2351. def getAttributeContent(self):
  2352. return self.attr_content
  2353. def fromDom(self, node):
  2354. self.content = []
  2355. self.setAttributes(node)
  2356. contents = self.getContents(node)
  2357. indx = 0
  2358. num = len(contents)
  2359. component = SplitQName(contents[indx].getTagName())[1]
  2360. if component == 'annotation':
  2361. self.annotation = Annotation(self)
  2362. self.annotation.fromDom(contents[indx])
  2363. indx += 1
  2364. component = SplitQName(contents[indx].getTagName())[1]
  2365. content = []
  2366. while indx < num:
  2367. component = SplitQName(contents[indx].getTagName())[1]
  2368. if component == 'attribute':
  2369. if contents[indx].hasattr('ref'):
  2370. content.append(AttributeReference(self))
  2371. else:
  2372. content.append(LocalAttributeDeclaration(self))
  2373. elif component == 'attributeGroup':
  2374. content.append(AttributeGroupReference(self))
  2375. elif component == 'anyAttribute':
  2376. content.append(AttributeWildCard(self))
  2377. elif component == 'simpleType':
  2378. self.content.append(AnonymousSimpleType(self))
  2379. self.content[-1].fromDom(contents[indx])
  2380. else:
  2381. raise SchemaError, 'Unknown component (%s)'\
  2382. %(contents[indx].getTagName())
  2383. content[-1].fromDom(contents[indx])
  2384. indx += 1
  2385. self.attr_content = tuple(content)
  2386. class LocalComplexType(ComplexType,\
  2387. LocalMarker):
  2388. """<complexType>
  2389. parents:
  2390. element
  2391. attributes:
  2392. id -- ID
  2393. mixed -- boolean, false
  2394. contents:
  2395. annotation?, (simpleContent | complexContent |
  2396. ((group | all | choice | sequence)?, (attribute | attributeGroup)*, anyAttribute?))
  2397. """
  2398. required = []
  2399. attributes = {'id':None,
  2400. 'mixed':0}
  2401. tag = 'complexType'
  2402. class SimpleType(XMLSchemaComponent,\
  2403. DefinitionMarker,\
  2404. SimpleMarker):
  2405. """<simpleType name>
  2406. parents:
  2407. redefine, schema
  2408. attributes:
  2409. id -- ID
  2410. name -- NCName, required
  2411. final -- ('#all' | ('extension' | 'restriction' | 'list' | 'union')*),
  2412. schema.finalDefault
  2413. contents:
  2414. annotation?, (restriction | list | union)
  2415. """
  2416. required = ['name']
  2417. attributes = {'id':None,
  2418. 'name':None,
  2419. 'final':lambda self: self._parent().getFinalDefault()}
  2420. contents = {'xsd':['annotation', 'restriction', 'list', 'union']}
  2421. tag = 'simpleType'
  2422. def __init__(self, parent):
  2423. XMLSchemaComponent.__init__(self, parent)
  2424. self.annotation = None
  2425. self.content = None
  2426. def getElementDeclaration(self, attribute):
  2427. raise Warning, 'invalid operation for <%s>' %self.tag
  2428. def getTypeDefinition(self, attribute):
  2429. raise Warning, 'invalid operation for <%s>' %self.tag
  2430. def fromDom(self, node):
  2431. self.setAttributes(node)
  2432. contents = self.getContents(node)
  2433. for child in contents:
  2434. component = SplitQName(child.getTagName())[1]
  2435. if component == 'annotation':
  2436. self.annotation = Annotation(self)
  2437. self.annotation.fromDom(child)
  2438. continue
  2439. break
  2440. else:
  2441. return
  2442. if component == 'restriction':
  2443. self.content = self.__class__.Restriction(self)
  2444. elif component == 'list':
  2445. self.content = self.__class__.List(self)
  2446. elif component == 'union':
  2447. self.content = self.__class__.Union(self)
  2448. else:
  2449. raise SchemaError, 'Unknown component (%s)' %(component)
  2450. self.content.fromDom(child)
  2451. class Restriction(XMLSchemaComponent,\
  2452. RestrictionMarker):
  2453. """<restriction base>
  2454. parents:
  2455. simpleType
  2456. attributes:
  2457. id -- ID
  2458. base -- QName, required or simpleType child
  2459. contents:
  2460. annotation?, simpleType?, (enumeration | length |
  2461. maxExclusive | maxInclusive | maxLength | minExclusive |
  2462. minInclusive | minLength | pattern | fractionDigits |
  2463. totalDigits | whiteSpace)*
  2464. """
  2465. attributes = {'id':None,
  2466. 'base':None }
  2467. contents = {'xsd':['annotation', 'simpleType']+RestrictionMarker.facets}
  2468. tag = 'restriction'
  2469. def __init__(self, parent):
  2470. XMLSchemaComponent.__init__(self, parent)
  2471. self.annotation = None
  2472. self.content = None
  2473. self.facets = None
  2474. def getAttributeBase(self):
  2475. return XMLSchemaComponent.getAttribute(self, 'base')
  2476. def getTypeDefinition(self, attribute='base'):
  2477. return XMLSchemaComponent.getTypeDefinition(self, attribute)
  2478. def getSimpleTypeContent(self):
  2479. for el in self.content:
  2480. if el.isSimple(): return el
  2481. return None
  2482. def fromDom(self, node):
  2483. self.facets = []
  2484. self.setAttributes(node)
  2485. contents = self.getContents(node)
  2486. content = []
  2487. for indx in range(len(contents)):
  2488. component = SplitQName(contents[indx].getTagName())[1]
  2489. if (component == 'annotation') and (not indx):
  2490. self.annotation = Annotation(self)
  2491. self.annotation.fromDom(contents[indx])
  2492. continue
  2493. elif (component == 'simpleType') and (not indx or indx == 1):
  2494. content.append(AnonymousSimpleType(self))
  2495. content[-1].fromDom(contents[indx])
  2496. elif component in RestrictionMarker.facets:
  2497. self.facets.append(contents[indx])
  2498. else:
  2499. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  2500. self.content = tuple(content)
  2501. class Union(XMLSchemaComponent,
  2502. UnionMarker):
  2503. """<union>
  2504. parents:
  2505. simpleType
  2506. attributes:
  2507. id -- ID
  2508. memberTypes -- list of QNames, required or simpleType child.
  2509. contents:
  2510. annotation?, simpleType*
  2511. """
  2512. attributes = {'id':None,
  2513. 'memberTypes':None }
  2514. contents = {'xsd':['annotation', 'simpleType']}
  2515. tag = 'union'
  2516. def __init__(self, parent):
  2517. XMLSchemaComponent.__init__(self, parent)
  2518. self.annotation = None
  2519. self.content = None
  2520. def fromDom(self, node):
  2521. self.setAttributes(node)
  2522. contents = self.getContents(node)
  2523. content = []
  2524. for indx in range(len(contents)):
  2525. component = SplitQName(contents[indx].getTagName())[1]
  2526. if (component == 'annotation') and (not indx):
  2527. self.annotation = Annotation(self)
  2528. self.annotation.fromDom(contents[indx])
  2529. elif (component == 'simpleType'):
  2530. content.append(AnonymousSimpleType(self))
  2531. content[-1].fromDom(contents[indx])
  2532. else:
  2533. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  2534. self.content = tuple(content)
  2535. class List(XMLSchemaComponent,
  2536. ListMarker):
  2537. """<list>
  2538. parents:
  2539. simpleType
  2540. attributes:
  2541. id -- ID
  2542. itemType -- QName, required or simpleType child.
  2543. contents:
  2544. annotation?, simpleType?
  2545. """
  2546. attributes = {'id':None,
  2547. 'itemType':None }
  2548. contents = {'xsd':['annotation', 'simpleType']}
  2549. tag = 'list'
  2550. def __init__(self, parent):
  2551. XMLSchemaComponent.__init__(self, parent)
  2552. self.annotation = None
  2553. self.content = None
  2554. def getItemType(self):
  2555. return self.attributes.get('itemType')
  2556. def getTypeDefinition(self, attribute='itemType'):
  2557. """
  2558. return the type refered to by itemType attribute or
  2559. the simpleType content. If returns None, then the
  2560. type refered to by itemType is primitive.
  2561. """
  2562. tp = XMLSchemaComponent.getTypeDefinition(self, attribute)
  2563. return tp or self.content
  2564. def fromDom(self, node):
  2565. self.annotation = None
  2566. self.content = None
  2567. self.setAttributes(node)
  2568. contents = self.getContents(node)
  2569. for indx in range(len(contents)):
  2570. component = SplitQName(contents[indx].getTagName())[1]
  2571. if (component == 'annotation') and (not indx):
  2572. self.annotation = Annotation(self)
  2573. self.annotation.fromDom(contents[indx])
  2574. elif (component == 'simpleType'):
  2575. self.content = AnonymousSimpleType(self)
  2576. self.content.fromDom(contents[indx])
  2577. break
  2578. else:
  2579. raise SchemaError, 'Unknown component (%s)' %(i.getTagName())
  2580. class AnonymousSimpleType(SimpleType,\
  2581. SimpleMarker,\
  2582. LocalMarker):
  2583. """<simpleType>
  2584. parents:
  2585. attribute, element, list, restriction, union
  2586. attributes:
  2587. id -- ID
  2588. contents:
  2589. annotation?, (restriction | list | union)
  2590. """
  2591. required = []
  2592. attributes = {'id':None}
  2593. tag = 'simpleType'
  2594. class Redefine:
  2595. """<redefine>
  2596. parents:
  2597. attributes:
  2598. contents:
  2599. """
  2600. tag = 'redefine'
  2601. ###########################
  2602. ###########################
  2603. if sys.version_info[:2] >= (2, 2):
  2604. tupleClass = tuple
  2605. else:
  2606. import UserTuple
  2607. tupleClass = UserTuple.UserTuple
  2608. class TypeDescriptionComponent(tupleClass):
  2609. """Tuple of length 2, consisting of
  2610. a namespace and unprefixed name.
  2611. """
  2612. def __init__(self, args):
  2613. """args -- (namespace, name)
  2614. Remove the name's prefix, irrelevant.
  2615. """
  2616. if len(args) != 2:
  2617. raise TypeError, 'expecting tuple (namespace, name), got %s' %args
  2618. elif args[1].find(':') >= 0:
  2619. args = (args[0], SplitQName(args[1])[1])
  2620. tuple.__init__(self, args)
  2621. return
  2622. def getTargetNamespace(self):
  2623. return self[0]
  2624. def getName(self):
  2625. return self[1]