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.
 
 
 

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