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.
 
 
 

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