You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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