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