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.
 
 
 

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