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.
 
 
 

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