blob: 61fe1550355dafc14e24620546056398ec546559 [file] [log] [blame]
Armin Rigo9ed73062005-12-14 18:10:45 +00001#
2# ElementTree
Florent Xiclunaf15351d2010-03-13 23:24:31 +00003# $Id: ElementTree.py 3440 2008-07-18 14:45:01Z fredrik $
Armin Rigo9ed73062005-12-14 18:10:45 +00004#
Florent Xiclunaf15351d2010-03-13 23:24:31 +00005# light-weight XML support for Python 2.3 and later.
Armin Rigo9ed73062005-12-14 18:10:45 +00006#
Florent Xiclunaf15351d2010-03-13 23:24:31 +00007# history (since 1.2.6):
8# 2005-11-12 fl added tostringlist/fromstringlist helpers
9# 2006-07-05 fl merged in selected changes from the 1.3 sandbox
10# 2006-07-05 fl removed support for 2.1 and earlier
11# 2007-06-21 fl added deprecation/future warnings
12# 2007-08-25 fl added doctype hook, added parser version attribute etc
13# 2007-08-26 fl added new serializer code (better namespace handling, etc)
14# 2007-08-27 fl warn for broken /tag searches on tree level
15# 2007-09-02 fl added html/text methods to serializer (experimental)
16# 2007-09-05 fl added method argument to tostring/tostringlist
17# 2007-09-06 fl improved error handling
18# 2007-09-13 fl added itertext, iterfind; assorted cleanups
19# 2007-12-15 fl added C14N hooks, copy method (experimental)
Armin Rigo9ed73062005-12-14 18:10:45 +000020#
Florent Xiclunaf15351d2010-03-13 23:24:31 +000021# Copyright (c) 1999-2008 by Fredrik Lundh. All rights reserved.
Armin Rigo9ed73062005-12-14 18:10:45 +000022#
23# fredrik@pythonware.com
24# http://www.pythonware.com
25#
26# --------------------------------------------------------------------
27# The ElementTree toolkit is
28#
Florent Xiclunaf15351d2010-03-13 23:24:31 +000029# Copyright (c) 1999-2008 by Fredrik Lundh
Armin Rigo9ed73062005-12-14 18:10:45 +000030#
31# By obtaining, using, and/or copying this software and/or its
32# associated documentation, you agree that you have read, understood,
33# and will comply with the following terms and conditions:
34#
35# Permission to use, copy, modify, and distribute this software and
36# its associated documentation for any purpose and without fee is
37# hereby granted, provided that the above copyright notice appears in
38# all copies, and that both that copyright notice and this permission
39# notice appear in supporting documentation, and that the name of
40# Secret Labs AB or the author not be used in advertising or publicity
41# pertaining to distribution of the software without specific, written
42# prior permission.
43#
44# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
45# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
46# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
47# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
48# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
49# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
50# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
51# OF THIS SOFTWARE.
52# --------------------------------------------------------------------
53
Fredrik Lundh63168a52005-12-14 22:29:34 +000054# Licensed to PSF under a Contributor Agreement.
Florent Xiclunaf15351d2010-03-13 23:24:31 +000055# See http://www.python.org/psf/license for licensing details.
Fredrik Lundh63168a52005-12-14 22:29:34 +000056
Armin Rigo9ed73062005-12-14 18:10:45 +000057__all__ = [
58 # public symbols
59 "Comment",
60 "dump",
61 "Element", "ElementTree",
Florent Xiclunaf15351d2010-03-13 23:24:31 +000062 "fromstring", "fromstringlist",
Armin Rigo9ed73062005-12-14 18:10:45 +000063 "iselement", "iterparse",
Florent Xiclunaf15351d2010-03-13 23:24:31 +000064 "parse", "ParseError",
Armin Rigo9ed73062005-12-14 18:10:45 +000065 "PI", "ProcessingInstruction",
66 "QName",
67 "SubElement",
Florent Xiclunaf15351d2010-03-13 23:24:31 +000068 "tostring", "tostringlist",
Armin Rigo9ed73062005-12-14 18:10:45 +000069 "TreeBuilder",
Florent Xiclunaf15351d2010-03-13 23:24:31 +000070 "VERSION",
Florent Xiclunaa72a98f2012-02-13 11:03:30 +010071 "XML", "XMLID",
Thomas Wouters0e3f5912006-08-11 14:57:12 +000072 "XMLParser", "XMLTreeBuilder",
Florent Xiclunaa72a98f2012-02-13 11:03:30 +010073 "register_namespace",
Armin Rigo9ed73062005-12-14 18:10:45 +000074 ]
75
Florent Xiclunaf15351d2010-03-13 23:24:31 +000076VERSION = "1.3.0"
77
Armin Rigo9ed73062005-12-14 18:10:45 +000078##
79# The <b>Element</b> type is a flexible container object, designed to
80# store hierarchical data structures in memory. The type can be
81# described as a cross between a list and a dictionary.
82# <p>
83# Each element has a number of properties associated with it:
84# <ul>
85# <li>a <i>tag</i>. This is a string identifying what kind of data
86# this element represents (the element type, in other words).</li>
87# <li>a number of <i>attributes</i>, stored in a Python dictionary.</li>
88# <li>a <i>text</i> string.</li>
89# <li>an optional <i>tail</i> string.</li>
90# <li>a number of <i>child elements</i>, stored in a Python sequence</li>
91# </ul>
92#
Florent Xiclunaf15351d2010-03-13 23:24:31 +000093# To create an element instance, use the {@link #Element} constructor
94# or the {@link #SubElement} factory function.
Armin Rigo9ed73062005-12-14 18:10:45 +000095# <p>
96# The {@link #ElementTree} class can be used to wrap an element
97# structure, and convert it from and to XML.
98##
99
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000100import sys
101import re
102import warnings
Armin Rigo9ed73062005-12-14 18:10:45 +0000103
Eli Bendersky27cbb192012-06-15 09:03:19 +0300104from . import ElementPath
Armin Rigo9ed73062005-12-14 18:10:45 +0000105
Armin Rigo9ed73062005-12-14 18:10:45 +0000106
107##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000108# Parser error. This is a subclass of <b>SyntaxError</b>.
Armin Rigo9ed73062005-12-14 18:10:45 +0000109# <p>
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000110# In addition to the exception value, an exception instance contains a
111# specific exception code in the <b>code</b> attribute, and the line and
112# column of the error in the <b>position</b> attribute.
113
114class ParseError(SyntaxError):
115 pass
116
117# --------------------------------------------------------------------
118
119##
120# Checks if an object appears to be a valid element object.
Armin Rigo9ed73062005-12-14 18:10:45 +0000121#
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000122# @param An element instance.
123# @return A true value if this is an element object.
124# @defreturn flag
125
126def iselement(element):
Florent Xiclunaa72a98f2012-02-13 11:03:30 +0100127 # FIXME: not sure about this;
128 # isinstance(element, Element) or look for tag/attrib/text attributes
129 return hasattr(element, 'tag')
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000130
131##
132# Element class. This class defines the Element interface, and
133# provides a reference implementation of this interface.
134# <p>
135# The element name, attribute names, and attribute values can be
136# either ASCII strings (ordinary Python strings containing only 7-bit
137# ASCII characters) or Unicode strings.
138#
139# @param tag The element name.
140# @param attrib An optional dictionary, containing element attributes.
141# @param **extra Additional attributes, given as keyword arguments.
Armin Rigo9ed73062005-12-14 18:10:45 +0000142# @see Element
143# @see SubElement
144# @see Comment
145# @see ProcessingInstruction
146
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000147class Element:
Armin Rigo9ed73062005-12-14 18:10:45 +0000148 # <tag attrib>text<child/>...</tag>tail
149
150 ##
151 # (Attribute) Element tag.
152
153 tag = None
154
155 ##
156 # (Attribute) Element attribute dictionary. Where possible, use
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000157 # {@link #Element.get},
158 # {@link #Element.set},
159 # {@link #Element.keys}, and
160 # {@link #Element.items} to access
Armin Rigo9ed73062005-12-14 18:10:45 +0000161 # element attributes.
162
163 attrib = None
164
165 ##
166 # (Attribute) Text before first subelement. This is either a
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000167 # string or the value None. Note that if there was no text, this
168 # attribute may be either None or an empty string, depending on
169 # the parser.
Armin Rigo9ed73062005-12-14 18:10:45 +0000170
171 text = None
172
173 ##
174 # (Attribute) Text after this element's end tag, but before the
175 # next sibling element's start tag. This is either a string or
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000176 # the value None. Note that if there was no text, this attribute
177 # may be either None or an empty string, depending on the parser.
Armin Rigo9ed73062005-12-14 18:10:45 +0000178
179 tail = None # text after end tag, if any
180
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000181 # constructor
182
183 def __init__(self, tag, attrib={}, **extra):
Eli Bendersky737b1732012-05-29 06:02:56 +0300184 if not isinstance(attrib, dict):
185 raise TypeError("attrib must be dict, not %s" % (
186 attrib.__class__.__name__,))
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000187 attrib = attrib.copy()
188 attrib.update(extra)
Armin Rigo9ed73062005-12-14 18:10:45 +0000189 self.tag = tag
190 self.attrib = attrib
191 self._children = []
192
193 def __repr__(self):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000194 return "<Element %s at 0x%x>" % (repr(self.tag), id(self))
Armin Rigo9ed73062005-12-14 18:10:45 +0000195
196 ##
197 # Creates a new element object of the same type as this element.
198 #
199 # @param tag Element tag.
200 # @param attrib Element attributes, given as a dictionary.
201 # @return A new element instance.
202
203 def makeelement(self, tag, attrib):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000204 return self.__class__(tag, attrib)
Armin Rigo9ed73062005-12-14 18:10:45 +0000205
206 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000207 # (Experimental) Copies the current element. This creates a
208 # shallow copy; subelements will be shared with the original tree.
209 #
210 # @return A new element instance.
211
212 def copy(self):
213 elem = self.makeelement(self.tag, self.attrib)
214 elem.text = self.text
215 elem.tail = self.tail
216 elem[:] = self
217 return elem
218
219 ##
220 # Returns the number of subelements. Note that this only counts
221 # full elements; to check if there's any content in an element, you
222 # have to check both the length and the <b>text</b> attribute.
Armin Rigo9ed73062005-12-14 18:10:45 +0000223 #
224 # @return The number of subelements.
225
226 def __len__(self):
227 return len(self._children)
228
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000229 def __bool__(self):
230 warnings.warn(
231 "The behavior of this method will change in future versions. "
232 "Use specific 'len(elem)' or 'elem is not None' test instead.",
233 FutureWarning, stacklevel=2
234 )
235 return len(self._children) != 0 # emulate old behaviour, for now
236
Armin Rigo9ed73062005-12-14 18:10:45 +0000237 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000238 # Returns the given subelement, by index.
Armin Rigo9ed73062005-12-14 18:10:45 +0000239 #
240 # @param index What subelement to return.
241 # @return The given subelement.
242 # @exception IndexError If the given element does not exist.
243
244 def __getitem__(self, index):
245 return self._children[index]
246
247 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000248 # Replaces the given subelement, by index.
Armin Rigo9ed73062005-12-14 18:10:45 +0000249 #
250 # @param index What subelement to replace.
251 # @param element The new element value.
252 # @exception IndexError If the given element does not exist.
Armin Rigo9ed73062005-12-14 18:10:45 +0000253
254 def __setitem__(self, index, element):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000255 # if isinstance(index, slice):
256 # for elt in element:
257 # assert iselement(elt)
258 # else:
259 # assert iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000260 self._children[index] = element
261
262 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000263 # Deletes the given subelement, by index.
Armin Rigo9ed73062005-12-14 18:10:45 +0000264 #
265 # @param index What subelement to delete.
266 # @exception IndexError If the given element does not exist.
267
268 def __delitem__(self, index):
269 del self._children[index]
270
271 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000272 # Adds a subelement to the end of this element. In document order,
273 # the new element will appear after the last existing subelement (or
274 # directly after the text, if it's the first subelement), but before
275 # the end tag for this element.
Armin Rigo9ed73062005-12-14 18:10:45 +0000276 #
277 # @param element The element to add.
Armin Rigo9ed73062005-12-14 18:10:45 +0000278
279 def append(self, element):
Eli Bendersky396e8fc2012-03-23 14:24:20 +0200280 self._assert_is_element(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000281 self._children.append(element)
282
283 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000284 # Appends subelements from a sequence.
285 #
286 # @param elements A sequence object with zero or more elements.
287 # @since 1.3
288
289 def extend(self, elements):
Eli Bendersky396e8fc2012-03-23 14:24:20 +0200290 for element in elements:
291 self._assert_is_element(element)
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000292 self._children.extend(elements)
293
294 ##
Armin Rigo9ed73062005-12-14 18:10:45 +0000295 # Inserts a subelement at the given position in this element.
296 #
297 # @param index Where to insert the new subelement.
Armin Rigo9ed73062005-12-14 18:10:45 +0000298
299 def insert(self, index, element):
Eli Bendersky396e8fc2012-03-23 14:24:20 +0200300 self._assert_is_element(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000301 self._children.insert(index, element)
302
Eli Bendersky396e8fc2012-03-23 14:24:20 +0200303 def _assert_is_element(self, e):
304 if not isinstance(e, Element):
305 raise TypeError('expected an Element, not %s' % type(e).__name__)
306
Armin Rigo9ed73062005-12-14 18:10:45 +0000307 ##
308 # Removes a matching subelement. Unlike the <b>find</b> methods,
309 # this method compares elements based on identity, not on tag
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000310 # value or contents. To remove subelements by other means, the
311 # easiest way is often to use a list comprehension to select what
312 # elements to keep, and use slice assignment to update the parent
313 # element.
Armin Rigo9ed73062005-12-14 18:10:45 +0000314 #
315 # @param element What element to remove.
316 # @exception ValueError If a matching element could not be found.
Armin Rigo9ed73062005-12-14 18:10:45 +0000317
318 def remove(self, element):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000319 # assert iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000320 self._children.remove(element)
321
322 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000323 # (Deprecated) Returns all subelements. The elements are returned
324 # in document order.
Armin Rigo9ed73062005-12-14 18:10:45 +0000325 #
326 # @return A list of subelements.
327 # @defreturn list of Element instances
328
329 def getchildren(self):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000330 warnings.warn(
331 "This method will be removed in future versions. "
332 "Use 'list(elem)' or iteration over elem instead.",
333 DeprecationWarning, stacklevel=2
334 )
Armin Rigo9ed73062005-12-14 18:10:45 +0000335 return self._children
336
337 ##
338 # Finds the first matching subelement, by tag name or path.
339 #
340 # @param path What element to look for.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000341 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000342 # @return The first matching element, or None if no element was found.
343 # @defreturn Element or None
344
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000345 def find(self, path, namespaces=None):
346 return ElementPath.find(self, path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000347
348 ##
349 # Finds text for the first matching subelement, by tag name or path.
350 #
351 # @param path What element to look for.
352 # @param default What to return if the element was not found.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000353 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000354 # @return The text content of the first matching element, or the
355 # default value no element was found. Note that if the element
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000356 # is found, but has no text content, this method returns an
Armin Rigo9ed73062005-12-14 18:10:45 +0000357 # empty string.
358 # @defreturn string
359
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000360 def findtext(self, path, default=None, namespaces=None):
361 return ElementPath.findtext(self, path, default, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000362
363 ##
364 # Finds all matching subelements, by tag name or path.
365 #
366 # @param path What element to look for.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000367 # @keyparam namespaces Optional namespace prefix map.
368 # @return A list or other sequence containing all matching elements,
Armin Rigo9ed73062005-12-14 18:10:45 +0000369 # in document order.
370 # @defreturn list of Element instances
371
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000372 def findall(self, path, namespaces=None):
373 return ElementPath.findall(self, path, namespaces)
374
375 ##
376 # Finds all matching subelements, by tag name or path.
377 #
378 # @param path What element to look for.
379 # @keyparam namespaces Optional namespace prefix map.
380 # @return An iterator or sequence containing all matching elements,
381 # in document order.
382 # @defreturn a generated sequence of Element instances
383
384 def iterfind(self, path, namespaces=None):
385 return ElementPath.iterfind(self, path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000386
387 ##
388 # Resets an element. This function removes all subelements, clears
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000389 # all attributes, and sets the <b>text</b> and <b>tail</b> attributes
390 # to None.
Armin Rigo9ed73062005-12-14 18:10:45 +0000391
392 def clear(self):
393 self.attrib.clear()
394 self._children = []
395 self.text = self.tail = None
396
397 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000398 # Gets an element attribute. Equivalent to <b>attrib.get</b>, but
399 # some implementations may handle this a bit more efficiently.
Armin Rigo9ed73062005-12-14 18:10:45 +0000400 #
401 # @param key What attribute to look for.
402 # @param default What to return if the attribute was not found.
403 # @return The attribute value, or the default value, if the
404 # attribute was not found.
405 # @defreturn string or None
406
407 def get(self, key, default=None):
408 return self.attrib.get(key, default)
409
410 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000411 # Sets an element attribute. Equivalent to <b>attrib[key] = value</b>,
412 # but some implementations may handle this a bit more efficiently.
Armin Rigo9ed73062005-12-14 18:10:45 +0000413 #
414 # @param key What attribute to set.
415 # @param value The attribute value.
416
417 def set(self, key, value):
418 self.attrib[key] = value
419
420 ##
421 # Gets a list of attribute names. The names are returned in an
422 # arbitrary order (just like for an ordinary Python dictionary).
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000423 # Equivalent to <b>attrib.keys()</b>.
Armin Rigo9ed73062005-12-14 18:10:45 +0000424 #
425 # @return A list of element attribute names.
426 # @defreturn list of strings
427
428 def keys(self):
429 return self.attrib.keys()
430
431 ##
432 # Gets element attributes, as a sequence. The attributes are
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000433 # returned in an arbitrary order. Equivalent to <b>attrib.items()</b>.
Armin Rigo9ed73062005-12-14 18:10:45 +0000434 #
435 # @return A list of (name, value) tuples for all attributes.
436 # @defreturn list of (string, string) tuples
437
438 def items(self):
439 return self.attrib.items()
440
441 ##
442 # Creates a tree iterator. The iterator loops over this element
443 # and all subelements, in document order, and returns all elements
444 # with a matching tag.
445 # <p>
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000446 # If the tree structure is modified during iteration, new or removed
447 # elements may or may not be included. To get a stable set, use the
448 # list() function on the iterator, and loop over the resulting list.
Armin Rigo9ed73062005-12-14 18:10:45 +0000449 #
450 # @param tag What tags to look for (default is to return all elements).
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000451 # @return An iterator containing all the matching elements.
452 # @defreturn iterator
Armin Rigo9ed73062005-12-14 18:10:45 +0000453
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000454 def iter(self, tag=None):
Armin Rigo9ed73062005-12-14 18:10:45 +0000455 if tag == "*":
456 tag = None
457 if tag is None or self.tag == tag:
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000458 yield self
459 for e in self._children:
460 for e in e.iter(tag):
461 yield e
462
463 # compatibility
464 def getiterator(self, tag=None):
465 # Change for a DeprecationWarning in 1.4
466 warnings.warn(
467 "This method will be removed in future versions. "
468 "Use 'elem.iter()' or 'list(elem.iter())' instead.",
469 PendingDeprecationWarning, stacklevel=2
470 )
471 return list(self.iter(tag))
472
473 ##
474 # Creates a text iterator. The iterator loops over this element
475 # and all subelements, in document order, and returns all inner
476 # text.
477 #
478 # @return An iterator containing all inner text.
479 # @defreturn iterator
480
481 def itertext(self):
482 tag = self.tag
483 if not isinstance(tag, str) and tag is not None:
484 return
485 if self.text:
486 yield self.text
487 for e in self:
488 for s in e.itertext():
489 yield s
490 if e.tail:
491 yield e.tail
Armin Rigo9ed73062005-12-14 18:10:45 +0000492
493# compatibility
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000494_Element = _ElementInterface = Element
Armin Rigo9ed73062005-12-14 18:10:45 +0000495
496##
497# Subelement factory. This function creates an element instance, and
498# appends it to an existing element.
499# <p>
500# The element name, attribute names, and attribute values can be
501# either 8-bit ASCII strings or Unicode strings.
502#
503# @param parent The parent element.
504# @param tag The subelement name.
505# @param attrib An optional dictionary, containing element attributes.
506# @param **extra Additional attributes, given as keyword arguments.
507# @return An element instance.
508# @defreturn Element
509
510def SubElement(parent, tag, attrib={}, **extra):
511 attrib = attrib.copy()
512 attrib.update(extra)
513 element = parent.makeelement(tag, attrib)
514 parent.append(element)
515 return element
516
517##
518# Comment element factory. This factory function creates a special
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000519# element that will be serialized as an XML comment by the standard
520# serializer.
Armin Rigo9ed73062005-12-14 18:10:45 +0000521# <p>
522# The comment string can be either an 8-bit ASCII string or a Unicode
523# string.
524#
525# @param text A string containing the comment string.
526# @return An element instance, representing a comment.
527# @defreturn Element
528
529def Comment(text=None):
530 element = Element(Comment)
531 element.text = text
532 return element
533
534##
535# PI element factory. This factory function creates a special element
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000536# that will be serialized as an XML processing instruction by the standard
537# serializer.
Armin Rigo9ed73062005-12-14 18:10:45 +0000538#
539# @param target A string containing the PI target.
540# @param text A string containing the PI contents, if any.
541# @return An element instance, representing a PI.
542# @defreturn Element
543
544def ProcessingInstruction(target, text=None):
545 element = Element(ProcessingInstruction)
546 element.text = target
547 if text:
548 element.text = element.text + " " + text
549 return element
550
551PI = ProcessingInstruction
552
553##
554# QName wrapper. This can be used to wrap a QName attribute value, in
555# order to get proper namespace handling on output.
556#
557# @param text A string containing the QName value, in the form {uri}local,
558# or, if the tag argument is given, the URI part of a QName.
559# @param tag Optional tag. If given, the first argument is interpreted as
560# an URI, and this argument is interpreted as a local name.
561# @return An opaque object, representing the QName.
562
563class QName:
564 def __init__(self, text_or_uri, tag=None):
565 if tag:
566 text_or_uri = "{%s}%s" % (text_or_uri, tag)
567 self.text = text_or_uri
568 def __str__(self):
569 return self.text
Georg Brandlb56c0e22010-12-09 18:10:27 +0000570 def __repr__(self):
Georg Brandlc95c9182010-12-09 18:26:02 +0000571 return '<QName %r>' % (self.text,)
Armin Rigo9ed73062005-12-14 18:10:45 +0000572 def __hash__(self):
573 return hash(self.text)
Mark Dickinsona56c4672009-01-27 18:17:45 +0000574 def __le__(self, other):
Armin Rigo9ed73062005-12-14 18:10:45 +0000575 if isinstance(other, QName):
Mark Dickinsona56c4672009-01-27 18:17:45 +0000576 return self.text <= other.text
577 return self.text <= other
578 def __lt__(self, other):
579 if isinstance(other, QName):
580 return self.text < other.text
581 return self.text < other
582 def __ge__(self, other):
583 if isinstance(other, QName):
584 return self.text >= other.text
585 return self.text >= other
586 def __gt__(self, other):
587 if isinstance(other, QName):
588 return self.text > other.text
589 return self.text > other
590 def __eq__(self, other):
591 if isinstance(other, QName):
592 return self.text == other.text
593 return self.text == other
594 def __ne__(self, other):
595 if isinstance(other, QName):
596 return self.text != other.text
597 return self.text != other
Armin Rigo9ed73062005-12-14 18:10:45 +0000598
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000599# --------------------------------------------------------------------
600
Armin Rigo9ed73062005-12-14 18:10:45 +0000601##
602# ElementTree wrapper class. This class represents an entire element
603# hierarchy, and adds some extra support for serialization to and from
604# standard XML.
605#
606# @param element Optional root element.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000607# @keyparam file Optional file handle or file name. If given, the
Armin Rigo9ed73062005-12-14 18:10:45 +0000608# tree is initialized with the contents of this XML file.
609
610class ElementTree:
611
612 def __init__(self, element=None, file=None):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000613 # assert element is None or iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000614 self._root = element # first node
615 if file:
616 self.parse(file)
617
618 ##
619 # Gets the root element for this tree.
620 #
621 # @return An element instance.
622 # @defreturn Element
623
624 def getroot(self):
625 return self._root
626
627 ##
628 # Replaces the root element for this tree. This discards the
629 # current contents of the tree, and replaces it with the given
630 # element. Use with care.
631 #
632 # @param element An element instance.
633
634 def _setroot(self, element):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000635 # assert iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000636 self._root = element
637
638 ##
639 # Loads an external XML document into this element tree.
640 #
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000641 # @param source A file name or file object. If a file object is
642 # given, it only has to implement a <b>read(n)</b> method.
643 # @keyparam parser An optional parser instance. If not given, the
644 # standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +0000645 # @return The document root element.
646 # @defreturn Element
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000647 # @exception ParseError If the parser fails to parse the document.
Armin Rigo9ed73062005-12-14 18:10:45 +0000648
649 def parse(self, source, parser=None):
Antoine Pitroue033e062010-10-29 10:38:18 +0000650 close_source = False
Armin Rigo9ed73062005-12-14 18:10:45 +0000651 if not hasattr(source, "read"):
652 source = open(source, "rb")
Antoine Pitroue033e062010-10-29 10:38:18 +0000653 close_source = True
654 try:
655 if not parser:
656 parser = XMLParser(target=TreeBuilder())
657 while 1:
658 data = source.read(65536)
659 if not data:
660 break
661 parser.feed(data)
662 self._root = parser.close()
663 return self._root
664 finally:
665 if close_source:
666 source.close()
Armin Rigo9ed73062005-12-14 18:10:45 +0000667
668 ##
669 # Creates a tree iterator for the root element. The iterator loops
670 # over all elements in this tree, in document order.
671 #
672 # @param tag What tags to look for (default is to return all elements)
673 # @return An iterator.
674 # @defreturn iterator
675
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000676 def iter(self, tag=None):
677 # assert self._root is not None
678 return self._root.iter(tag)
679
680 # compatibility
Armin Rigo9ed73062005-12-14 18:10:45 +0000681 def getiterator(self, tag=None):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000682 # Change for a DeprecationWarning in 1.4
683 warnings.warn(
684 "This method will be removed in future versions. "
685 "Use 'tree.iter()' or 'list(tree.iter())' instead.",
686 PendingDeprecationWarning, stacklevel=2
687 )
688 return list(self.iter(tag))
Armin Rigo9ed73062005-12-14 18:10:45 +0000689
690 ##
691 # Finds the first toplevel element with given tag.
692 # Same as getroot().find(path).
693 #
694 # @param path What element to look for.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000695 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000696 # @return The first matching element, or None if no element was found.
697 # @defreturn Element or None
698
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000699 def find(self, path, namespaces=None):
700 # assert self._root is not None
Armin Rigo9ed73062005-12-14 18:10:45 +0000701 if path[:1] == "/":
702 path = "." + path
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000703 warnings.warn(
704 "This search is broken in 1.3 and earlier, and will be "
705 "fixed in a future version. If you rely on the current "
706 "behaviour, change it to %r" % path,
707 FutureWarning, stacklevel=2
708 )
709 return self._root.find(path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000710
711 ##
712 # Finds the element text for the first toplevel element with given
713 # tag. Same as getroot().findtext(path).
714 #
715 # @param path What toplevel element to look for.
716 # @param default What to return if the element was not found.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000717 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000718 # @return The text content of the first matching element, or the
719 # default value no element was found. Note that if the element
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000720 # is found, but has no text content, this method returns an
Armin Rigo9ed73062005-12-14 18:10:45 +0000721 # empty string.
722 # @defreturn string
723
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000724 def findtext(self, path, default=None, namespaces=None):
725 # assert self._root is not None
Armin Rigo9ed73062005-12-14 18:10:45 +0000726 if path[:1] == "/":
727 path = "." + path
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000728 warnings.warn(
729 "This search is broken in 1.3 and earlier, and will be "
730 "fixed in a future version. If you rely on the current "
731 "behaviour, change it to %r" % path,
732 FutureWarning, stacklevel=2
733 )
734 return self._root.findtext(path, default, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000735
736 ##
737 # Finds all toplevel elements with the given tag.
738 # Same as getroot().findall(path).
739 #
740 # @param path What element to look for.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000741 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000742 # @return A list or iterator containing all matching elements,
743 # in document order.
744 # @defreturn list of Element instances
745
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000746 def findall(self, path, namespaces=None):
747 # assert self._root is not None
Armin Rigo9ed73062005-12-14 18:10:45 +0000748 if path[:1] == "/":
749 path = "." + path
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000750 warnings.warn(
751 "This search is broken in 1.3 and earlier, and will be "
752 "fixed in a future version. If you rely on the current "
753 "behaviour, change it to %r" % path,
754 FutureWarning, stacklevel=2
755 )
756 return self._root.findall(path, namespaces)
757
758 ##
759 # Finds all matching subelements, by tag name or path.
760 # Same as getroot().iterfind(path).
761 #
762 # @param path What element to look for.
763 # @keyparam namespaces Optional namespace prefix map.
764 # @return An iterator or sequence containing all matching elements,
765 # in document order.
766 # @defreturn a generated sequence of Element instances
767
768 def iterfind(self, path, namespaces=None):
769 # assert self._root is not None
770 if path[:1] == "/":
771 path = "." + path
772 warnings.warn(
773 "This search is broken in 1.3 and earlier, and will be "
774 "fixed in a future version. If you rely on the current "
775 "behaviour, change it to %r" % path,
776 FutureWarning, stacklevel=2
777 )
778 return self._root.iterfind(path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000779
780 ##
781 # Writes the element tree to a file, as XML.
782 #
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000783 # @def write(file, **options)
Armin Rigo9ed73062005-12-14 18:10:45 +0000784 # @param file A file name, or a file object opened for writing.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000785 # @param **options Options, given as keyword arguments.
Florent Xiclunac17f1722010-08-08 19:48:29 +0000786 # @keyparam encoding Optional output encoding (default is US-ASCII).
787 # Use "unicode" to return a Unicode string.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000788 # @keyparam method Optional output method ("xml", "html", "text" or
789 # "c14n"; default is "xml").
790 # @keyparam xml_declaration Controls if an XML declaration should
791 # be added to the file. Use False for never, True for always,
Florent Xiclunac17f1722010-08-08 19:48:29 +0000792 # None for only if not US-ASCII or UTF-8 or Unicode. None is default.
Armin Rigo9ed73062005-12-14 18:10:45 +0000793
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000794 def write(self, file_or_filename,
795 # keyword arguments
796 encoding=None,
797 xml_declaration=None,
798 default_namespace=None,
799 method=None):
800 # assert self._root is not None
801 if not method:
802 method = "xml"
803 elif method not in _serialize:
804 # FIXME: raise an ImportError for c14n if ElementC14N is missing?
805 raise ValueError("unknown method %r" % method)
Florent Xiclunac17f1722010-08-08 19:48:29 +0000806 if not encoding:
807 if method == "c14n":
808 encoding = "utf-8"
809 else:
810 encoding = "us-ascii"
811 elif encoding == str: # lxml.etree compatibility.
812 encoding = "unicode"
813 else:
814 encoding = encoding.lower()
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000815 if hasattr(file_or_filename, "write"):
816 file = file_or_filename
Armin Rigo9ed73062005-12-14 18:10:45 +0000817 else:
Florent Xiclunac17f1722010-08-08 19:48:29 +0000818 if encoding != "unicode":
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000819 file = open(file_or_filename, "wb")
Armin Rigo9ed73062005-12-14 18:10:45 +0000820 else:
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000821 file = open(file_or_filename, "w")
Florent Xiclunac17f1722010-08-08 19:48:29 +0000822 if encoding != "unicode":
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000823 def write(text):
824 try:
825 return file.write(text.encode(encoding,
826 "xmlcharrefreplace"))
827 except (TypeError, AttributeError):
828 _raise_serialization_error(text)
829 else:
830 write = file.write
Florent Xiclunac17f1722010-08-08 19:48:29 +0000831 if method == "xml" and (xml_declaration or
832 (xml_declaration is None and
833 encoding not in ("utf-8", "us-ascii", "unicode"))):
834 declared_encoding = encoding
835 if encoding == "unicode":
836 # Retrieve the default encoding for the xml declaration
837 import locale
838 declared_encoding = locale.getpreferredencoding()
839 write("<?xml version='1.0' encoding='%s'?>\n" % declared_encoding)
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000840 if method == "text":
841 _serialize_text(write, self._root)
842 else:
843 qnames, namespaces = _namespaces(self._root, default_namespace)
844 serialize = _serialize[method]
845 serialize(write, self._root, qnames, namespaces)
846 if file_or_filename is not file:
847 file.close()
848
849 def write_c14n(self, file):
850 # lxml.etree compatibility. use output method instead
851 return self.write(file, method="c14n")
Armin Rigo9ed73062005-12-14 18:10:45 +0000852
853# --------------------------------------------------------------------
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000854# serialization support
855
856def _namespaces(elem, default_namespace=None):
857 # identify namespaces used in this tree
858
859 # maps qnames to *encoded* prefix:local names
860 qnames = {None: None}
861
862 # maps uri:s to prefixes
863 namespaces = {}
864 if default_namespace:
865 namespaces[default_namespace] = ""
866
867 def add_qname(qname):
868 # calculate serialized qname representation
869 try:
870 if qname[:1] == "{":
871 uri, tag = qname[1:].rsplit("}", 1)
872 prefix = namespaces.get(uri)
873 if prefix is None:
874 prefix = _namespace_map.get(uri)
875 if prefix is None:
876 prefix = "ns%d" % len(namespaces)
877 if prefix != "xml":
878 namespaces[uri] = prefix
879 if prefix:
880 qnames[qname] = "%s:%s" % (prefix, tag)
881 else:
882 qnames[qname] = tag # default element
883 else:
884 if default_namespace:
885 # FIXME: can this be handled in XML 1.0?
886 raise ValueError(
887 "cannot use non-qualified names with "
888 "default_namespace option"
889 )
890 qnames[qname] = qname
891 except TypeError:
892 _raise_serialization_error(qname)
893
894 # populate qname and namespaces table
Eli Bendersky64d11e62012-06-15 07:42:50 +0300895 for elem in elem.iter():
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000896 tag = elem.tag
Senthil Kumaranec30b3d2010-11-09 02:36:59 +0000897 if isinstance(tag, QName):
898 if tag.text not in qnames:
899 add_qname(tag.text)
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000900 elif isinstance(tag, str):
901 if tag not in qnames:
902 add_qname(tag)
903 elif tag is not None and tag is not Comment and tag is not PI:
904 _raise_serialization_error(tag)
905 for key, value in elem.items():
906 if isinstance(key, QName):
907 key = key.text
908 if key not in qnames:
909 add_qname(key)
910 if isinstance(value, QName) and value.text not in qnames:
911 add_qname(value.text)
912 text = elem.text
913 if isinstance(text, QName) and text.text not in qnames:
914 add_qname(text.text)
915 return qnames, namespaces
916
917def _serialize_xml(write, elem, qnames, namespaces):
918 tag = elem.tag
919 text = elem.text
920 if tag is Comment:
921 write("<!--%s-->" % text)
922 elif tag is ProcessingInstruction:
923 write("<?%s?>" % text)
924 else:
925 tag = qnames[tag]
926 if tag is None:
927 if text:
928 write(_escape_cdata(text))
929 for e in elem:
930 _serialize_xml(write, e, qnames, None)
931 else:
932 write("<" + tag)
933 items = list(elem.items())
934 if items or namespaces:
935 if namespaces:
936 for v, k in sorted(namespaces.items(),
937 key=lambda x: x[1]): # sort on prefix
938 if k:
939 k = ":" + k
940 write(" xmlns%s=\"%s\"" % (
941 k,
942 _escape_attrib(v)
943 ))
944 for k, v in sorted(items): # lexical order
945 if isinstance(k, QName):
946 k = k.text
947 if isinstance(v, QName):
948 v = qnames[v.text]
949 else:
950 v = _escape_attrib(v)
951 write(" %s=\"%s\"" % (qnames[k], v))
952 if text or len(elem):
953 write(">")
954 if text:
955 write(_escape_cdata(text))
956 for e in elem:
957 _serialize_xml(write, e, qnames, None)
958 write("</" + tag + ">")
959 else:
960 write(" />")
961 if elem.tail:
962 write(_escape_cdata(elem.tail))
963
964HTML_EMPTY = ("area", "base", "basefont", "br", "col", "frame", "hr",
965 "img", "input", "isindex", "link", "meta" "param")
966
967try:
968 HTML_EMPTY = set(HTML_EMPTY)
969except NameError:
970 pass
971
972def _serialize_html(write, elem, qnames, namespaces):
973 tag = elem.tag
974 text = elem.text
975 if tag is Comment:
976 write("<!--%s-->" % _escape_cdata(text))
977 elif tag is ProcessingInstruction:
978 write("<?%s?>" % _escape_cdata(text))
979 else:
980 tag = qnames[tag]
981 if tag is None:
982 if text:
983 write(_escape_cdata(text))
984 for e in elem:
985 _serialize_html(write, e, qnames, None)
986 else:
987 write("<" + tag)
988 items = list(elem.items())
989 if items or namespaces:
990 if namespaces:
991 for v, k in sorted(namespaces.items(),
992 key=lambda x: x[1]): # sort on prefix
993 if k:
994 k = ":" + k
995 write(" xmlns%s=\"%s\"" % (
996 k,
997 _escape_attrib(v)
998 ))
999 for k, v in sorted(items): # lexical order
1000 if isinstance(k, QName):
1001 k = k.text
1002 if isinstance(v, QName):
1003 v = qnames[v.text]
1004 else:
1005 v = _escape_attrib_html(v)
1006 # FIXME: handle boolean attributes
1007 write(" %s=\"%s\"" % (qnames[k], v))
1008 write(">")
1009 tag = tag.lower()
1010 if text:
1011 if tag == "script" or tag == "style":
1012 write(text)
1013 else:
1014 write(_escape_cdata(text))
1015 for e in elem:
1016 _serialize_html(write, e, qnames, None)
1017 if tag not in HTML_EMPTY:
1018 write("</" + tag + ">")
1019 if elem.tail:
1020 write(_escape_cdata(elem.tail))
1021
1022def _serialize_text(write, elem):
1023 for part in elem.itertext():
1024 write(part)
1025 if elem.tail:
1026 write(elem.tail)
1027
1028_serialize = {
1029 "xml": _serialize_xml,
1030 "html": _serialize_html,
1031 "text": _serialize_text,
1032# this optional method is imported at the end of the module
1033# "c14n": _serialize_c14n,
1034}
Armin Rigo9ed73062005-12-14 18:10:45 +00001035
1036##
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001037# Registers a namespace prefix. The registry is global, and any
1038# existing mapping for either the given prefix or the namespace URI
1039# will be removed.
Armin Rigo9ed73062005-12-14 18:10:45 +00001040#
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001041# @param prefix Namespace prefix.
1042# @param uri Namespace uri. Tags and attributes in this namespace
1043# will be serialized with the given prefix, if at all possible.
1044# @exception ValueError If the prefix is reserved, or is otherwise
1045# invalid.
Armin Rigo9ed73062005-12-14 18:10:45 +00001046
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001047def register_namespace(prefix, uri):
1048 if re.match("ns\d+$", prefix):
1049 raise ValueError("Prefix format reserved for internal use")
Georg Brandl90b20672010-12-28 10:38:33 +00001050 for k, v in list(_namespace_map.items()):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001051 if k == uri or v == prefix:
1052 del _namespace_map[k]
1053 _namespace_map[uri] = prefix
1054
1055_namespace_map = {
1056 # "well-known" namespace prefixes
1057 "http://www.w3.org/XML/1998/namespace": "xml",
1058 "http://www.w3.org/1999/xhtml": "html",
1059 "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
1060 "http://schemas.xmlsoap.org/wsdl/": "wsdl",
1061 # xml schema
1062 "http://www.w3.org/2001/XMLSchema": "xs",
1063 "http://www.w3.org/2001/XMLSchema-instance": "xsi",
1064 # dublin core
1065 "http://purl.org/dc/elements/1.1/": "dc",
1066}
Florent Xicluna16395052012-02-16 23:28:35 +01001067# For tests and troubleshooting
1068register_namespace._namespace_map = _namespace_map
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001069
1070def _raise_serialization_error(text):
1071 raise TypeError(
1072 "cannot serialize %r (type %s)" % (text, type(text).__name__)
1073 )
1074
1075def _escape_cdata(text):
1076 # escape character data
1077 try:
1078 # it's worth avoiding do-nothing calls for strings that are
1079 # shorter than 500 character, or so. assume that's, by far,
1080 # the most common case in most applications.
1081 if "&" in text:
1082 text = text.replace("&", "&amp;")
1083 if "<" in text:
1084 text = text.replace("<", "&lt;")
1085 if ">" in text:
1086 text = text.replace(">", "&gt;")
1087 return text
1088 except (TypeError, AttributeError):
1089 _raise_serialization_error(text)
1090
1091def _escape_attrib(text):
1092 # escape attribute value
1093 try:
1094 if "&" in text:
1095 text = text.replace("&", "&amp;")
1096 if "<" in text:
1097 text = text.replace("<", "&lt;")
1098 if ">" in text:
1099 text = text.replace(">", "&gt;")
1100 if "\"" in text:
1101 text = text.replace("\"", "&quot;")
1102 if "\n" in text:
1103 text = text.replace("\n", "&#10;")
1104 return text
1105 except (TypeError, AttributeError):
1106 _raise_serialization_error(text)
1107
1108def _escape_attrib_html(text):
1109 # escape attribute value
1110 try:
1111 if "&" in text:
1112 text = text.replace("&", "&amp;")
1113 if ">" in text:
1114 text = text.replace(">", "&gt;")
1115 if "\"" in text:
1116 text = text.replace("\"", "&quot;")
1117 return text
1118 except (TypeError, AttributeError):
1119 _raise_serialization_error(text)
1120
1121# --------------------------------------------------------------------
1122
1123##
1124# Generates a string representation of an XML element, including all
Florent Xiclunac17f1722010-08-08 19:48:29 +00001125# subelements. If encoding is "unicode", the return type is a string;
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001126# otherwise it is a bytes array.
1127#
1128# @param element An Element instance.
Florent Xiclunac17f1722010-08-08 19:48:29 +00001129# @keyparam encoding Optional output encoding (default is US-ASCII).
1130# Use "unicode" to return a Unicode string.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001131# @keyparam method Optional output method ("xml", "html", "text" or
1132# "c14n"; default is "xml").
1133# @return An (optionally) encoded string containing the XML data.
1134# @defreturn string
1135
1136def tostring(element, encoding=None, method=None):
1137 class dummy:
1138 pass
1139 data = []
1140 file = dummy()
1141 file.write = data.append
1142 ElementTree(element).write(file, encoding, method=method)
Florent Xiclunac17f1722010-08-08 19:48:29 +00001143 if encoding in (str, "unicode"):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001144 return "".join(data)
Florent Xiclunac17f1722010-08-08 19:48:29 +00001145 else:
1146 return b"".join(data)
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001147
1148##
1149# Generates a string representation of an XML element, including all
Florent Xiclunac17f1722010-08-08 19:48:29 +00001150# subelements. If encoding is False, the string is returned as a
1151# sequence of string fragments; otherwise it is a sequence of
1152# bytestrings.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001153#
1154# @param element An Element instance.
1155# @keyparam encoding Optional output encoding (default is US-ASCII).
Florent Xiclunac17f1722010-08-08 19:48:29 +00001156# Use "unicode" to return a Unicode string.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001157# @keyparam method Optional output method ("xml", "html", "text" or
1158# "c14n"; default is "xml").
1159# @return A sequence object containing the XML data.
1160# @defreturn sequence
1161# @since 1.3
1162
1163def tostringlist(element, encoding=None, method=None):
1164 class dummy:
1165 pass
1166 data = []
1167 file = dummy()
1168 file.write = data.append
1169 ElementTree(element).write(file, encoding, method=method)
1170 # FIXME: merge small fragments into larger parts
1171 return data
Armin Rigo9ed73062005-12-14 18:10:45 +00001172
1173##
1174# Writes an element tree or element structure to sys.stdout. This
1175# function should be used for debugging only.
1176# <p>
1177# The exact output format is implementation dependent. In this
1178# version, it's written as an ordinary XML file.
1179#
1180# @param elem An element tree or an individual element.
1181
1182def dump(elem):
1183 # debugging
1184 if not isinstance(elem, ElementTree):
1185 elem = ElementTree(elem)
Florent Xiclunac17f1722010-08-08 19:48:29 +00001186 elem.write(sys.stdout, encoding="unicode")
Armin Rigo9ed73062005-12-14 18:10:45 +00001187 tail = elem.getroot().tail
1188 if not tail or tail[-1] != "\n":
1189 sys.stdout.write("\n")
1190
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001191# --------------------------------------------------------------------
1192# parsing
Armin Rigo9ed73062005-12-14 18:10:45 +00001193
1194##
1195# Parses an XML document into an element tree.
1196#
1197# @param source A filename or file object containing XML data.
1198# @param parser An optional parser instance. If not given, the
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001199# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001200# @return An ElementTree instance
1201
1202def parse(source, parser=None):
1203 tree = ElementTree()
1204 tree.parse(source, parser)
1205 return tree
1206
1207##
1208# Parses an XML document into an element tree incrementally, and reports
1209# what's going on to the user.
1210#
1211# @param source A filename or file object containing XML data.
1212# @param events A list of events to report back. If omitted, only "end"
1213# events are reported.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001214# @param parser An optional parser instance. If not given, the
1215# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001216# @return A (event, elem) iterator.
1217
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001218def iterparse(source, events=None, parser=None):
Antoine Pitroue033e062010-10-29 10:38:18 +00001219 close_source = False
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001220 if not hasattr(source, "read"):
1221 source = open(source, "rb")
Antoine Pitroue033e062010-10-29 10:38:18 +00001222 close_source = True
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001223 if not parser:
1224 parser = XMLParser(target=TreeBuilder())
Antoine Pitroue033e062010-10-29 10:38:18 +00001225 return _IterParseIterator(source, events, parser, close_source)
Armin Rigo9ed73062005-12-14 18:10:45 +00001226
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001227class _IterParseIterator:
1228
Antoine Pitroue033e062010-10-29 10:38:18 +00001229 def __init__(self, source, events, parser, close_source=False):
Armin Rigo9ed73062005-12-14 18:10:45 +00001230 self._file = source
Antoine Pitroue033e062010-10-29 10:38:18 +00001231 self._close_file = close_source
Armin Rigo9ed73062005-12-14 18:10:45 +00001232 self._events = []
1233 self._index = 0
Florent Xicluna91d51932011-11-01 23:31:09 +01001234 self._error = None
Armin Rigo9ed73062005-12-14 18:10:45 +00001235 self.root = self._root = None
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001236 self._parser = parser
Armin Rigo9ed73062005-12-14 18:10:45 +00001237 # wire up the parser for event reporting
1238 parser = self._parser._parser
1239 append = self._events.append
1240 if events is None:
1241 events = ["end"]
1242 for event in events:
1243 if event == "start":
1244 try:
1245 parser.ordered_attributes = 1
1246 parser.specified_attributes = 1
1247 def handler(tag, attrib_in, event=event, append=append,
1248 start=self._parser._start_list):
1249 append((event, start(tag, attrib_in)))
1250 parser.StartElementHandler = handler
1251 except AttributeError:
1252 def handler(tag, attrib_in, event=event, append=append,
1253 start=self._parser._start):
1254 append((event, start(tag, attrib_in)))
1255 parser.StartElementHandler = handler
1256 elif event == "end":
1257 def handler(tag, event=event, append=append,
1258 end=self._parser._end):
1259 append((event, end(tag)))
1260 parser.EndElementHandler = handler
1261 elif event == "start-ns":
1262 def handler(prefix, uri, event=event, append=append):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001263 append((event, (prefix or "", uri or "")))
Armin Rigo9ed73062005-12-14 18:10:45 +00001264 parser.StartNamespaceDeclHandler = handler
1265 elif event == "end-ns":
1266 def handler(prefix, event=event, append=append):
1267 append((event, None))
1268 parser.EndNamespaceDeclHandler = handler
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001269 else:
1270 raise ValueError("unknown event %r" % event)
Armin Rigo9ed73062005-12-14 18:10:45 +00001271
Georg Brandla18af4e2007-04-21 15:47:16 +00001272 def __next__(self):
Armin Rigo9ed73062005-12-14 18:10:45 +00001273 while 1:
1274 try:
1275 item = self._events[self._index]
Florent Xicluna91d51932011-11-01 23:31:09 +01001276 self._index += 1
Armin Rigo9ed73062005-12-14 18:10:45 +00001277 return item
Florent Xicluna91d51932011-11-01 23:31:09 +01001278 except IndexError:
1279 pass
1280 if self._error:
1281 e = self._error
1282 self._error = None
1283 raise e
1284 if self._parser is None:
1285 self.root = self._root
1286 if self._close_file:
1287 self._file.close()
1288 raise StopIteration
1289 # load event buffer
1290 del self._events[:]
1291 self._index = 0
1292 data = self._file.read(16384)
1293 if data:
1294 try:
1295 self._parser.feed(data)
1296 except SyntaxError as exc:
1297 self._error = exc
1298 else:
1299 self._root = self._parser.close()
1300 self._parser = None
Armin Rigo9ed73062005-12-14 18:10:45 +00001301
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001302 def __iter__(self):
1303 return self
Armin Rigo9ed73062005-12-14 18:10:45 +00001304
1305##
1306# Parses an XML document from a string constant. This function can
1307# be used to embed "XML literals" in Python code.
1308#
1309# @param source A string containing XML data.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001310# @param parser An optional parser instance. If not given, the
1311# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001312# @return An Element instance.
1313# @defreturn Element
1314
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001315def XML(text, parser=None):
1316 if not parser:
1317 parser = XMLParser(target=TreeBuilder())
Armin Rigo9ed73062005-12-14 18:10:45 +00001318 parser.feed(text)
1319 return parser.close()
1320
1321##
1322# Parses an XML document from a string constant, and also returns
1323# a dictionary which maps from element id:s to elements.
1324#
1325# @param source A string containing XML data.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001326# @param parser An optional parser instance. If not given, the
1327# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001328# @return A tuple containing an Element instance and a dictionary.
1329# @defreturn (Element, dictionary)
1330
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001331def XMLID(text, parser=None):
1332 if not parser:
1333 parser = XMLParser(target=TreeBuilder())
Armin Rigo9ed73062005-12-14 18:10:45 +00001334 parser.feed(text)
1335 tree = parser.close()
1336 ids = {}
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001337 for elem in tree.iter():
Armin Rigo9ed73062005-12-14 18:10:45 +00001338 id = elem.get("id")
1339 if id:
1340 ids[id] = elem
1341 return tree, ids
1342
1343##
1344# Parses an XML document from a string constant. Same as {@link #XML}.
1345#
1346# @def fromstring(text)
1347# @param source A string containing XML data.
1348# @return An Element instance.
1349# @defreturn Element
1350
1351fromstring = XML
1352
1353##
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001354# Parses an XML document from a sequence of string fragments.
Armin Rigo9ed73062005-12-14 18:10:45 +00001355#
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001356# @param sequence A list or other sequence containing XML data fragments.
1357# @param parser An optional parser instance. If not given, the
1358# standard {@link XMLParser} parser is used.
1359# @return An Element instance.
1360# @defreturn Element
1361# @since 1.3
Armin Rigo9ed73062005-12-14 18:10:45 +00001362
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001363def fromstringlist(sequence, parser=None):
1364 if not parser:
1365 parser = XMLParser(target=TreeBuilder())
1366 for text in sequence:
1367 parser.feed(text)
1368 return parser.close()
1369
1370# --------------------------------------------------------------------
Armin Rigo9ed73062005-12-14 18:10:45 +00001371
1372##
1373# Generic element structure builder. This builder converts a sequence
1374# of {@link #TreeBuilder.start}, {@link #TreeBuilder.data}, and {@link
1375# #TreeBuilder.end} method calls to a well-formed element structure.
1376# <p>
1377# You can use this class to build an element structure using a custom XML
1378# parser, or a parser for some other XML-like format.
1379#
1380# @param element_factory Optional element factory. This factory
1381# is called to create new Element instances, as necessary.
1382
1383class TreeBuilder:
1384
1385 def __init__(self, element_factory=None):
1386 self._data = [] # data collector
1387 self._elem = [] # element stack
1388 self._last = None # last element
1389 self._tail = None # true if we're after an end tag
1390 if element_factory is None:
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001391 element_factory = Element
Armin Rigo9ed73062005-12-14 18:10:45 +00001392 self._factory = element_factory
1393
1394 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001395 # Flushes the builder buffers, and returns the toplevel document
Armin Rigo9ed73062005-12-14 18:10:45 +00001396 # element.
1397 #
1398 # @return An Element instance.
1399 # @defreturn Element
1400
1401 def close(self):
1402 assert len(self._elem) == 0, "missing end tags"
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001403 assert self._last is not None, "missing toplevel element"
Armin Rigo9ed73062005-12-14 18:10:45 +00001404 return self._last
1405
1406 def _flush(self):
1407 if self._data:
1408 if self._last is not None:
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001409 text = "".join(self._data)
Armin Rigo9ed73062005-12-14 18:10:45 +00001410 if self._tail:
1411 assert self._last.tail is None, "internal error (tail)"
1412 self._last.tail = text
1413 else:
1414 assert self._last.text is None, "internal error (text)"
1415 self._last.text = text
1416 self._data = []
1417
1418 ##
1419 # Adds text to the current element.
1420 #
1421 # @param data A string. This should be either an 8-bit string
1422 # containing ASCII text, or a Unicode string.
1423
1424 def data(self, data):
1425 self._data.append(data)
1426
1427 ##
1428 # Opens a new element.
1429 #
1430 # @param tag The element name.
1431 # @param attrib A dictionary containing element attributes.
1432 # @return The opened element.
1433 # @defreturn Element
1434
1435 def start(self, tag, attrs):
1436 self._flush()
1437 self._last = elem = self._factory(tag, attrs)
1438 if self._elem:
1439 self._elem[-1].append(elem)
1440 self._elem.append(elem)
1441 self._tail = 0
1442 return elem
1443
1444 ##
1445 # Closes the current element.
1446 #
1447 # @param tag The element name.
1448 # @return The closed element.
1449 # @defreturn Element
1450
1451 def end(self, tag):
1452 self._flush()
1453 self._last = self._elem.pop()
1454 assert self._last.tag == tag,\
1455 "end tag mismatch (expected %s, got %s)" % (
1456 self._last.tag, tag)
1457 self._tail = 1
1458 return self._last
1459
1460##
1461# Element structure builder for XML source data, based on the
1462# <b>expat</b> parser.
1463#
1464# @keyparam target Target object. If omitted, the builder uses an
1465# instance of the standard {@link #TreeBuilder} class.
1466# @keyparam html Predefine HTML entities. This flag is not supported
1467# by the current implementation.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001468# @keyparam encoding Optional encoding. If given, the value overrides
1469# the encoding specified in the XML file.
Armin Rigo9ed73062005-12-14 18:10:45 +00001470# @see #ElementTree
1471# @see #TreeBuilder
1472
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001473class XMLParser:
Armin Rigo9ed73062005-12-14 18:10:45 +00001474
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001475 def __init__(self, html=0, target=None, encoding=None):
Armin Rigo9ed73062005-12-14 18:10:45 +00001476 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001477 from xml.parsers import expat
Armin Rigo9ed73062005-12-14 18:10:45 +00001478 except ImportError:
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001479 try:
1480 import pyexpat as expat
1481 except ImportError:
1482 raise ImportError(
1483 "No module named expat; use SimpleXMLTreeBuilder instead"
1484 )
1485 parser = expat.ParserCreate(encoding, "}")
Armin Rigo9ed73062005-12-14 18:10:45 +00001486 if target is None:
1487 target = TreeBuilder()
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001488 # underscored names are provided for compatibility only
1489 self.parser = self._parser = parser
1490 self.target = self._target = target
1491 self._error = expat.error
Armin Rigo9ed73062005-12-14 18:10:45 +00001492 self._names = {} # name memo cache
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001493 # main callbacks
Armin Rigo9ed73062005-12-14 18:10:45 +00001494 parser.DefaultHandlerExpand = self._default
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001495 if hasattr(target, 'start'):
1496 parser.StartElementHandler = self._start
1497 if hasattr(target, 'end'):
1498 parser.EndElementHandler = self._end
1499 if hasattr(target, 'data'):
1500 parser.CharacterDataHandler = target.data
1501 # miscellaneous callbacks
1502 if hasattr(target, 'comment'):
1503 parser.CommentHandler = target.comment
1504 if hasattr(target, 'pi'):
1505 parser.ProcessingInstructionHandler = target.pi
Armin Rigo9ed73062005-12-14 18:10:45 +00001506 # let expat do the buffering, if supported
1507 try:
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001508 parser.buffer_text = 1
Armin Rigo9ed73062005-12-14 18:10:45 +00001509 except AttributeError:
1510 pass
1511 # use new-style attribute handling, if supported
1512 try:
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001513 parser.ordered_attributes = 1
1514 parser.specified_attributes = 1
1515 if hasattr(target, 'start'):
1516 parser.StartElementHandler = self._start_list
Armin Rigo9ed73062005-12-14 18:10:45 +00001517 except AttributeError:
1518 pass
Armin Rigo9ed73062005-12-14 18:10:45 +00001519 self._doctype = None
1520 self.entity = {}
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001521 try:
1522 self.version = "Expat %d.%d.%d" % expat.version_info
1523 except AttributeError:
1524 pass # unknown
1525
1526 def _raiseerror(self, value):
1527 err = ParseError(value)
1528 err.code = value.code
1529 err.position = value.lineno, value.offset
1530 raise err
Armin Rigo9ed73062005-12-14 18:10:45 +00001531
Armin Rigo9ed73062005-12-14 18:10:45 +00001532 def _fixname(self, key):
1533 # expand qname, and convert name string to ascii, if possible
1534 try:
1535 name = self._names[key]
1536 except KeyError:
1537 name = key
1538 if "}" in name:
1539 name = "{" + name
Martin v. Löwisf30bb0e2007-07-28 11:40:46 +00001540 self._names[key] = name
Armin Rigo9ed73062005-12-14 18:10:45 +00001541 return name
1542
1543 def _start(self, tag, attrib_in):
1544 fixname = self._fixname
1545 tag = fixname(tag)
1546 attrib = {}
1547 for key, value in attrib_in.items():
Martin v. Löwisf30bb0e2007-07-28 11:40:46 +00001548 attrib[fixname(key)] = value
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001549 return self.target.start(tag, attrib)
Armin Rigo9ed73062005-12-14 18:10:45 +00001550
1551 def _start_list(self, tag, attrib_in):
1552 fixname = self._fixname
1553 tag = fixname(tag)
1554 attrib = {}
1555 if attrib_in:
1556 for i in range(0, len(attrib_in), 2):
Martin v. Löwisf30bb0e2007-07-28 11:40:46 +00001557 attrib[fixname(attrib_in[i])] = attrib_in[i+1]
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001558 return self.target.start(tag, attrib)
Armin Rigo9ed73062005-12-14 18:10:45 +00001559
Armin Rigo9ed73062005-12-14 18:10:45 +00001560 def _end(self, tag):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001561 return self.target.end(self._fixname(tag))
1562
Armin Rigo9ed73062005-12-14 18:10:45 +00001563 def _default(self, text):
1564 prefix = text[:1]
1565 if prefix == "&":
1566 # deal with undefined entities
1567 try:
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001568 data_handler = self.target.data
1569 except AttributeError:
1570 return
1571 try:
1572 data_handler(self.entity[text[1:-1]])
Armin Rigo9ed73062005-12-14 18:10:45 +00001573 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001574 from xml.parsers import expat
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001575 err = expat.error(
Armin Rigo9ed73062005-12-14 18:10:45 +00001576 "undefined entity %s: line %d, column %d" %
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001577 (text, self.parser.ErrorLineNumber,
1578 self.parser.ErrorColumnNumber)
Armin Rigo9ed73062005-12-14 18:10:45 +00001579 )
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001580 err.code = 11 # XML_ERROR_UNDEFINED_ENTITY
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001581 err.lineno = self.parser.ErrorLineNumber
1582 err.offset = self.parser.ErrorColumnNumber
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001583 raise err
Armin Rigo9ed73062005-12-14 18:10:45 +00001584 elif prefix == "<" and text[:9] == "<!DOCTYPE":
1585 self._doctype = [] # inside a doctype declaration
1586 elif self._doctype is not None:
1587 # parse doctype contents
1588 if prefix == ">":
1589 self._doctype = None
1590 return
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001591 text = text.strip()
Armin Rigo9ed73062005-12-14 18:10:45 +00001592 if not text:
1593 return
1594 self._doctype.append(text)
1595 n = len(self._doctype)
1596 if n > 2:
1597 type = self._doctype[1]
1598 if type == "PUBLIC" and n == 4:
1599 name, type, pubid, system = self._doctype
Florent Xiclunaa1c974a2012-07-07 13:16:44 +02001600 if pubid:
1601 pubid = pubid[1:-1]
Armin Rigo9ed73062005-12-14 18:10:45 +00001602 elif type == "SYSTEM" and n == 3:
1603 name, type, system = self._doctype
1604 pubid = None
1605 else:
1606 return
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001607 if hasattr(self.target, "doctype"):
1608 self.target.doctype(name, pubid, system[1:-1])
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001609 elif self.doctype != self._XMLParser__doctype:
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001610 # warn about deprecated call
1611 self._XMLParser__doctype(name, pubid, system[1:-1])
1612 self.doctype(name, pubid, system[1:-1])
Armin Rigo9ed73062005-12-14 18:10:45 +00001613 self._doctype = None
1614
1615 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001616 # (Deprecated) Handles a doctype declaration.
Armin Rigo9ed73062005-12-14 18:10:45 +00001617 #
1618 # @param name Doctype name.
1619 # @param pubid Public identifier.
1620 # @param system System identifier.
1621
1622 def doctype(self, name, pubid, system):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001623 """This method of XMLParser is deprecated."""
1624 warnings.warn(
1625 "This method of XMLParser is deprecated. Define doctype() "
1626 "method on the TreeBuilder target.",
1627 DeprecationWarning,
1628 )
1629
1630 # sentinel, if doctype is redefined in a subclass
1631 __doctype = doctype
Armin Rigo9ed73062005-12-14 18:10:45 +00001632
1633 ##
1634 # Feeds data to the parser.
1635 #
1636 # @param data Encoded data.
1637
1638 def feed(self, data):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001639 try:
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001640 self.parser.Parse(data, 0)
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001641 except self._error as v:
1642 self._raiseerror(v)
Armin Rigo9ed73062005-12-14 18:10:45 +00001643
1644 ##
1645 # Finishes feeding data to the parser.
1646 #
1647 # @return An element structure.
1648 # @defreturn Element
1649
1650 def close(self):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001651 try:
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001652 self.parser.Parse("", 1) # end of data
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001653 except self._error as v:
1654 self._raiseerror(v)
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001655 try:
Florent Xiclunafb067462012-03-05 11:42:49 +01001656 close_handler = self.target.close
1657 except AttributeError:
1658 pass
1659 else:
1660 return close_handler()
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001661 finally:
1662 # get rid of circular references
1663 del self.parser, self._parser
1664 del self.target, self._target
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001665
Florent Xiclunaa72a98f2012-02-13 11:03:30 +01001666
1667# Import the C accelerators
1668try:
1669 # Element, SubElement, ParseError, TreeBuilder, XMLParser
1670 from _elementtree import *
1671except ImportError:
1672 pass
1673else:
1674 # Overwrite 'ElementTree.parse' and 'iterparse' to use the C XMLParser
1675
1676 class ElementTree(ElementTree):
1677 def parse(self, source, parser=None):
1678 close_source = False
1679 if not hasattr(source, 'read'):
1680 source = open(source, 'rb')
1681 close_source = True
1682 try:
1683 if parser is not None:
1684 while True:
1685 data = source.read(65536)
1686 if not data:
1687 break
1688 parser.feed(data)
1689 self._root = parser.close()
1690 else:
1691 parser = XMLParser()
1692 self._root = parser._parse(source)
1693 return self._root
1694 finally:
1695 if close_source:
1696 source.close()
1697
1698 class iterparse:
1699 root = None
1700 def __init__(self, file, events=None):
1701 self._close_file = False
1702 if not hasattr(file, 'read'):
1703 file = open(file, 'rb')
1704 self._close_file = True
1705 self._file = file
1706 self._events = []
1707 self._index = 0
1708 self._error = None
1709 self.root = self._root = None
1710 b = TreeBuilder()
1711 self._parser = XMLParser(b)
1712 self._parser._setevents(self._events, events)
1713
1714 def __next__(self):
1715 while True:
1716 try:
1717 item = self._events[self._index]
1718 self._index += 1
1719 return item
1720 except IndexError:
1721 pass
1722 if self._error:
1723 e = self._error
1724 self._error = None
1725 raise e
1726 if self._parser is None:
1727 self.root = self._root
1728 if self._close_file:
1729 self._file.close()
1730 raise StopIteration
1731 # load event buffer
1732 del self._events[:]
1733 self._index = 0
1734 data = self._file.read(16384)
1735 if data:
1736 try:
1737 self._parser.feed(data)
1738 except SyntaxError as exc:
1739 self._error = exc
1740 else:
1741 self._root = self._parser.close()
1742 self._parser = None
1743
1744 def __iter__(self):
1745 return self
1746
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001747# compatibility
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001748XMLTreeBuilder = XMLParser
1749
1750# workaround circular import.
1751try:
1752 from ElementC14N import _serialize_c14n
1753 _serialize["c14n"] = _serialize_c14n
1754except ImportError:
1755 pass