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.
 
 
 

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