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.
 
 
 

2843 lines
98 KiB

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