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.
 
 
 

2901 lines
99 KiB

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