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.
 
 
 

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