Package pyxb :: Package binding :: Module saxer
[hide private]
[frames] | no frames]

Source Code for Module pyxb.binding.saxer

  1  # Copyright 2009, Peter A. Bigot 
  2  # 
  3  # Licensed under the Apache License, Version 2.0 (the "License"); you may 
  4  # not use this file except in compliance with the License. You may obtain a 
  5  # copy of the License at: 
  6  # 
  7  #            http://www.apache.org/licenses/LICENSE-2.0 
  8  # 
  9  # Unless required by applicable law or agreed to in writing, software 
 10  # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
 11  # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
 12  # License for the specific language governing permissions and limitations 
 13  # under the License. 
 14   
 15  """This module contains support for generating bindings from an XML stream 
 16  using a SAX parser.""" 
 17   
 18  import xml.dom 
 19  import pyxb.namespace 
 20  import pyxb.utils.saxutils 
 21  import pyxb.utils.saxdom 
 22  import pyxb.utils.utility 
 23  import basis 
 24  from pyxb.namespace.builtin import XMLSchema_instance as XSI 
 25   
26 -class _SAXElementState (pyxb.utils.saxutils.SAXElementState):
27 """State required to generate bindings for a specific element. 28 29 If the document being parsed includes references to unrecognized elements, 30 a DOM instance of the element and its content is created and treated as a 31 wildcard element. 32 """ 33 34 # An expanded name corresponding to xsi:nil 35 __XSINilTuple = XSI.nil.uriTuple() 36 37 # The binding instance being created for this element. When the 38 # element type has simple content, the binding instance cannot be 39 # created until the end of the element has been reached and the 40 # content of the element has been processed accumulated for use in 41 # the instance constructor. When the element type has complex 42 # content, the binding instance must be created at the start of 43 # the element, so contained elements can be properly stored. 44 __bindingInstance = None 45 46 # The schema binding for the element being constructed. 47 __elementBinding = None 48
49 - def setElementBinding (self, element_binding):
50 """Record the binding to be used for this element. 51 52 Generally ignored, except at the top level this is the only way to 53 associate a binding instance created from an xsi:type description with 54 a specific element.""" 55 self.__elementBinding = element_binding
56 57 # The nearest enclosing complex type definition
58 - def enclosingCTD (self):
59 """The nearest enclosing complex type definition, as used for 60 resolving local element/attribute names. 61 62 @return: An instance of L{basis.complexTypeDefinition}, or C{None} if 63 the element is top-level 64 """ 65 return self.__enclosingCTD
66 __enclosingCTD = None 67 68 # The factory that is called to create a binding instance for this 69 # element; None if the binding instance was created at the start 70 # of the element. 71 __delayedConstructor = None 72 73 # An xml.sax.xmlreader.Attributes instance providing the 74 # attributes for the element. 75 __attributes = None 76 77 # An xml.dom.Node corresponding to the (sub-)document 78 __domDocument = None 79 80 __domDepth = None 81
82 - def __init__ (self, **kw):
83 super(_SAXElementState, self).__init__(**kw) 84 self.__bindingInstance = None 85 parent_state = self.parentState() 86 if isinstance(parent_state, _SAXElementState): 87 self.__enclosingCTD = parent_state.enclosingCTD() 88 self.__domDocument = parent_state.__domDocument 89 if self.__domDocument is not None: 90 self.__domDepth = parent_state.__domDepth + 1
91
92 - def setEnclosingCTD (self, enclosing_ctd):
93 """Set the enclosing complex type definition for this element. 94 95 @param enclosing_ctd: The scope for a local element. 96 @type enclosing_ctd: L{basis.complexTypeDefinition} 97 @return: C{self} 98 """ 99 self.__enclosingCTD = enclosing_ctd
100 101 # Create the binding instance for this element.
102 - def __constructElement (self, new_object_factory, attrs, content=None):
103 kw = { '_from_xml' : True } 104 105 # Note whether the node is marked nil 106 if attrs.has_key(self.__XSINilTuple): 107 kw['_nil'] = pyxb.binding.datatypes.boolean(attrs.getValue(self.__XSINilTuple)) 108 109 if content is None: 110 content = [] 111 self.__bindingInstance = new_object_factory(*content, **kw) 112 if isinstance(self.__bindingInstance, pyxb.utils.utility.Locatable_mixin): 113 self.__bindingInstance._setLocation(self.location()) 114 115 # Record the namespace context so users of the binding can 116 # interpret QNames within the attributes and content. 117 self.__bindingInstance._setNamespaceContext(self.__namespaceContext) 118 119 # Set instance attributes 120 # NB: attrs implements the SAX AttributesNS interface, meaning 121 # that names are pairs of (namespaceURI, localName), just like we 122 # want them to be. 123 for attr_name in self.__attributes.getNames(): 124 attr_en = pyxb.namespace.ExpandedName(attr_name) 125 # Ignore xmlns and xsi attributes; we've already handled those 126 if attr_en.namespace() in ( pyxb.namespace.XMLNamespaces, XSI ): 127 continue 128 self.__bindingInstance._setAttribute(attr_en, attrs.getValue(attr_name)) 129 130 return self.__bindingInstance
131
132 - def inDOMMode (self):
133 return self.__domDocument is not None
134
135 - def enterDOMMode (self, attrs):
136 """Actions upon first encountering an element for which we cannot create a binding. 137 138 Invoking this transitions the parser into DOM mode, creating a new DOM 139 document that will represent this element including its content.""" 140 assert not self.__domDocument 141 self.__domDocument = pyxb.utils.saxdom.Document(namespace_context=self.namespaceContext()) 142 self.__domDepth = 0 143 return self.startDOMElement(attrs)
144
145 - def startDOMElement (self, attrs):
146 """Actions upon entering an element that is part of a DOM subtree.""" 147 self.__domDepth += 1 148 #print 'Enter level %d with %s' % (self.__domDepth, self.expandedName()) 149 self.__attributes = pyxb.utils.saxdom.NamedNodeMap() 150 ns_ctx = self.namespaceContext() 151 for name in attrs.getNames(): 152 attr_en = pyxb.namespace.ExpandedName(name) 153 self.__attributes._addItem(pyxb.utils.saxdom.Attr(expanded_name=attr_en, namespace_context=ns_ctx, value=attrs.getValue(name), location=self.location()))
154
155 - def endDOMElement (self):
156 """Actions upon leaving an element that is part of a DOM subtree.""" 157 ns_ctx = self.namespaceContext() 158 element = pyxb.utils.saxdom.Element(namespace_context=ns_ctx, expanded_name=self.expandedName(), attributes=self.__attributes, location=self.location()) 159 for ( content, element_use, maybe_element ) in self.content(): 160 if isinstance(content, xml.dom.Node): 161 element.appendChild(content) 162 else: 163 element.appendChild(pyxb.utils.saxdom.Text(content, namespace_context=ns_ctx)) 164 #print 'Leaving level %d with %s' % (self.__domDepth, self.expandedName()) 165 self.__domDepth -= 1 166 if 0 == self.__domDepth: 167 self.__domDocument.appendChild(element) 168 #pyxb.utils.saxdom._DumpDOM(self.__domDocument) 169 self.__domDepth = None 170 self.__domDocument = None 171 parent_state = self.parentState() 172 parent_state.addElementContent(element, None) 173 return element
174
175 - def startBindingElement (self, type_class, new_object_factory, element_use, attrs):
176 """Actions upon entering an element that will produce a binding instance. 177 178 The element use is recorded. If the type is a subclass of 179 L{basis.simpleTypeDefinition}, a delayed constructor is recorded so 180 the binding instance can be created upon completion of the element; 181 otherwise, a binding instance is created and stored. The attributes 182 are used to initialize the binding instance (now, or upon element 183 end). 184 185 @param type_class: The Python type of the binding instance 186 @type type_class: subclass of L{basis._TypeBinding_mixin} 187 @param new_object_factory: A callable object that creates an instance of the C{type_class} 188 @param element_use: The element use with which the binding instance is associated. Will be C{None} for top-level elements 189 @type element_use: L{basis.element} 190 @param attrs: The XML attributes associated with the element 191 @type attrs: C{xml.sax.xmlreader.Attributes} 192 @return: The generated binding instance, or C{None} if creation is delayed 193 """ 194 self.__delayedConstructor = None 195 self.__elementUse = element_use 196 self.__attributes = attrs 197 if type_class._IsSimpleTypeContent(): 198 self.__delayedConstructor = new_object_factory 199 else: 200 self.__constructElement(new_object_factory, attrs) 201 return self.__bindingInstance
202
203 - def endBindingElement (self):
204 """Perform any end-of-element processing. 205 206 For simple type instances, this creates the binding instance. 207 @return: The generated binding instance 208 """ 209 if self.__delayedConstructor is not None: 210 args = [] 211 for (content, element_use, maybe_element) in self.__content: 212 assert not maybe_element 213 assert element_use is None 214 assert isinstance(content, basestring) 215 args.append(content) 216 assert 1 >= len(args), 'Unexpected STD content %s' % (args,) 217 self.__constructElement(self.__delayedConstructor, self.__attributes, args) 218 else: 219 #print 'Extending %s by content %s' % (self.__bindingInstance, self.__content,) 220 for (content, element_use, maybe_element) in self.__content: 221 self.__bindingInstance.append(content, element_use, maybe_element, require_validation=pyxb._ParsingRequiresValid) 222 parent_state = self.parentState() 223 if parent_state is not None: 224 parent_state.addElementContent(self.__bindingInstance, self.__elementUse) 225 # As CreateFromDOM does, validate the resulting element 226 if self.__bindingInstance._element() is None: 227 self.__bindingInstance._setElement(self.__elementBinding) 228 if pyxb._ParsingRequiresValid: 229 self.__bindingInstance.validateBinding() 230 return self.__bindingInstance
231
232 -class PyXBSAXHandler (pyxb.utils.saxutils.BaseSAXHandler):
233 """A SAX handler class which generates a binding instance for a document 234 through a streaming parser. 235 236 An example of using this to parse the document held in the string C{xmls} is:: 237 238 import pyxb.binding.saxer 239 import StringIO 240 241 saxer = pyxb.binding.saxer.make_parser() 242 handler = saxer.getContentHandler() 243 saxer.parse(StringIO.StringIO(xml)) 244 instance = handler.rootObject() 245 246 """ 247 248 # Whether invocation of handler methods should be traced 249 __trace = False 250 251 # An expanded name corresponding to xsi:type 252 __XSITypeTuple = XSI.type.uriTuple() 253 254 __domHandler = None 255 __domDepth = None 256
257 - def rootObject (self):
258 """Return the binding object corresponding to the top-most 259 element in the document 260 261 @return: An instance of L{basis._TypeBinding_mixin} (most usually a 262 L{basis.complexTypeDefinition}. 263 264 @raise pyxb.UnrecognizedElementError: No binding could be found to 265 match the top-level element in the document.""" 266 if not isinstance(self.__rootObject, basis._TypeBinding_mixin): 267 # Happens if the top-level element got processed as a DOM instance. 268 raise pyxb.UnrecognizedElementError(dom_node=self.__rootObject) 269 return self.__rootObject
270 __rootObject = None 271
272 - def reset (self):
273 """Reset the state of the handler in preparation for processing a new 274 document. 275 276 @return: C{self} 277 """ 278 super(PyXBSAXHandler, self).reset() 279 self.__rootObject = None 280 return self
281
282 - def __init__ (self, **kw):
283 """Create a parser instance for converting XML to bindings. 284 285 @keyword element_state_constructor: Overridden with the value 286 L{_SAXElementState} before invoking the L{superclass 287 constructor<pyxb.utils.saxutils.BaseSAXHandler.__init__>}. 288 """ 289 290 kw.setdefault('element_state_constructor', _SAXElementState) 291 super(PyXBSAXHandler, self).__init__(**kw) 292 self.reset()
293
294 - def startElementNS (self, name, qname, attrs):
295 (this_state, parent_state, ns_ctx, name_en) = super(PyXBSAXHandler, self).startElementNS(name, qname, attrs) 296 297 # Delegate processing if in DOM mode 298 if this_state.inDOMMode(): 299 return this_state.startDOMElement(attrs) 300 301 # Resolve the element within the appropriate context. Note 302 # that global elements have no use, only the binding. 303 if parent_state.enclosingCTD() is not None: 304 (element_binding, element_use) = parent_state.enclosingCTD()._ElementBindingUseForName(name_en) 305 else: 306 element_use = None 307 element_binding = name_en.elementBinding() 308 this_state.setElementBinding(element_binding) 309 310 # Non-root elements should have an element use, from which we can 311 # extract the binding if we couldn't find one elsewhere. (Keep any 312 # current binding, since it may be a member of a substitution group.) 313 if (element_use is not None) and (element_binding is None): 314 assert self.__rootObject is not None 315 element_binding = element_use.elementBinding() 316 assert element_binding is not None 317 318 # Start knowing nothing 319 type_class = None 320 if element_binding is not None: 321 element_binding = element_binding.elementForName(name) 322 type_class = element_binding.typeDefinition() 323 324 # Process an xsi:type attribute, if present 325 if attrs.has_key(self.__XSITypeTuple): 326 (did_replace, type_class) = XSI._InterpretTypeAttribute(attrs.getValue(self.__XSITypeTuple), ns_ctx, self.fallbackNamespace(), type_class) 327 if did_replace: 328 element_binding = None 329 330 if type_class is None: 331 # Bother. We don't know what this thing is. But that's not an 332 # error, if the schema accepts wildcards. For consistency with 333 # the DOM-based interface, we need to build a DOM node. 334 return this_state.enterDOMMode(attrs) 335 336 if element_binding is not None: 337 # Invoke binding __call__ method not Factory, so can check for 338 # abstract elements. 339 new_object_factory = element_binding 340 else: 341 new_object_factory = type_class.Factory 342 343 # Update the enclosing complex type definition for this 344 # element state. 345 assert type_class is not None 346 if issubclass(type_class, pyxb.binding.basis.complexTypeDefinition): 347 this_state.setEnclosingCTD(type_class) 348 else: 349 this_state.setEnclosingCTD(parent_state.enclosingCTD()) 350 351 # Process the element start. This may or may not return a 352 # binding object. 353 binding_object = this_state.startBindingElement(type_class, new_object_factory, element_use, attrs) 354 355 # If the top-level element has complex content, this sets the 356 # root object. If it has simple content, see endElementNS. 357 if self.__rootObject is None: 358 self.__rootObject = binding_object
359
360 - def endElementNS (self, name, qname):
361 this_state = super(PyXBSAXHandler, self).endElementNS(name, qname) 362 if this_state.inDOMMode(): 363 # Delegate processing if in DOM mode. Note that completing this 364 # element may take us out of DOM mode. In any case, the returned 365 # binding object is a DOM element instance. 366 binding_object = this_state.endDOMElement() 367 else: 368 # Process the element end. This will return a binding object, 369 # either the one created at the start or the one created at 370 # the end. 371 binding_object = this_state.endBindingElement() 372 assert binding_object is not None 373 374 # If we don't have a root object, save it. No, there is not a 375 # problem doing this on the close of the element. If the 376 # top-level element has complex content, the object was 377 # created on start, and the root object has been assigned. If 378 # it has simple content, then there are no internal elements 379 # that could slip in and set this before we get to it here. 380 if self.__rootObject is None: 381 self.__rootObject = binding_object
382
383 -def make_parser (*args, **kw):
384 """Extend L{pyxb.utils.saxutils.make_parser} to change the default 385 C{content_handler_constructor} to be L{PyXBSAXHandler}. 386 """ 387 kw.setdefault('content_handler_constructor', PyXBSAXHandler) 388 return pyxb.utils.saxutils.make_parser(*args, **kw)
389 390 ## Local Variables: 391 ## fill-column:78 392 ## End: 393