blob: e068fc2443d73a16febb090a20cee604ddf709f2 [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
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000104class _SimpleElementPath:
105 # emulate pre-1.2 find/findtext/findall behaviour
106 def find(self, element, tag, namespaces=None):
107 for elem in element:
108 if elem.tag == tag:
109 return elem
110 return None
111 def findtext(self, element, tag, default=None, namespaces=None):
112 elem = self.find(element, tag)
113 if elem is None:
114 return default
115 return elem.text or ""
116 def iterfind(self, element, tag, namespaces=None):
117 if tag[:3] == ".//":
118 for elem in element.iter(tag[3:]):
119 yield elem
120 for elem in element:
121 if elem.tag == tag:
122 yield elem
123 def findall(self, element, tag, namespaces=None):
124 return list(self.iterfind(element, tag, namespaces))
Armin Rigo9ed73062005-12-14 18:10:45 +0000125
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000126try:
127 from . import ElementPath
128except ImportError:
129 ElementPath = _SimpleElementPath()
Armin Rigo9ed73062005-12-14 18:10:45 +0000130
131##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000132# Parser error. This is a subclass of <b>SyntaxError</b>.
Armin Rigo9ed73062005-12-14 18:10:45 +0000133# <p>
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000134# In addition to the exception value, an exception instance contains a
135# specific exception code in the <b>code</b> attribute, and the line and
136# column of the error in the <b>position</b> attribute.
137
138class ParseError(SyntaxError):
139 pass
140
141# --------------------------------------------------------------------
142
143##
144# Checks if an object appears to be a valid element object.
Armin Rigo9ed73062005-12-14 18:10:45 +0000145#
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000146# @param An element instance.
147# @return A true value if this is an element object.
148# @defreturn flag
149
150def iselement(element):
Florent Xiclunaa72a98f2012-02-13 11:03:30 +0100151 # FIXME: not sure about this;
152 # isinstance(element, Element) or look for tag/attrib/text attributes
153 return hasattr(element, 'tag')
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000154
155##
156# Element class. This class defines the Element interface, and
157# provides a reference implementation of this interface.
158# <p>
159# The element name, attribute names, and attribute values can be
160# either ASCII strings (ordinary Python strings containing only 7-bit
161# ASCII characters) or Unicode strings.
162#
163# @param tag The element name.
164# @param attrib An optional dictionary, containing element attributes.
165# @param **extra Additional attributes, given as keyword arguments.
Armin Rigo9ed73062005-12-14 18:10:45 +0000166# @see Element
167# @see SubElement
168# @see Comment
169# @see ProcessingInstruction
170
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000171class Element:
Armin Rigo9ed73062005-12-14 18:10:45 +0000172 # <tag attrib>text<child/>...</tag>tail
173
174 ##
175 # (Attribute) Element tag.
176
177 tag = None
178
179 ##
180 # (Attribute) Element attribute dictionary. Where possible, use
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000181 # {@link #Element.get},
182 # {@link #Element.set},
183 # {@link #Element.keys}, and
184 # {@link #Element.items} to access
Armin Rigo9ed73062005-12-14 18:10:45 +0000185 # element attributes.
186
187 attrib = None
188
189 ##
190 # (Attribute) Text before first subelement. This is either a
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000191 # string or the value None. Note that if there was no text, this
192 # attribute may be either None or an empty string, depending on
193 # the parser.
Armin Rigo9ed73062005-12-14 18:10:45 +0000194
195 text = None
196
197 ##
198 # (Attribute) Text after this element's end tag, but before the
199 # next sibling element's start tag. This is either a string or
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000200 # the value None. Note that if there was no text, this attribute
201 # may be either None or an empty string, depending on the parser.
Armin Rigo9ed73062005-12-14 18:10:45 +0000202
203 tail = None # text after end tag, if any
204
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000205 # constructor
206
207 def __init__(self, tag, attrib={}, **extra):
Eli Bendersky737b1732012-05-29 06:02:56 +0300208 if not isinstance(attrib, dict):
209 raise TypeError("attrib must be dict, not %s" % (
210 attrib.__class__.__name__,))
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000211 attrib = attrib.copy()
212 attrib.update(extra)
Armin Rigo9ed73062005-12-14 18:10:45 +0000213 self.tag = tag
214 self.attrib = attrib
215 self._children = []
216
217 def __repr__(self):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000218 return "<Element %s at 0x%x>" % (repr(self.tag), id(self))
Armin Rigo9ed73062005-12-14 18:10:45 +0000219
220 ##
221 # Creates a new element object of the same type as this element.
222 #
223 # @param tag Element tag.
224 # @param attrib Element attributes, given as a dictionary.
225 # @return A new element instance.
226
227 def makeelement(self, tag, attrib):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000228 return self.__class__(tag, attrib)
Armin Rigo9ed73062005-12-14 18:10:45 +0000229
230 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000231 # (Experimental) Copies the current element. This creates a
232 # shallow copy; subelements will be shared with the original tree.
233 #
234 # @return A new element instance.
235
236 def copy(self):
237 elem = self.makeelement(self.tag, self.attrib)
238 elem.text = self.text
239 elem.tail = self.tail
240 elem[:] = self
241 return elem
242
243 ##
244 # Returns the number of subelements. Note that this only counts
245 # full elements; to check if there's any content in an element, you
246 # have to check both the length and the <b>text</b> attribute.
Armin Rigo9ed73062005-12-14 18:10:45 +0000247 #
248 # @return The number of subelements.
249
250 def __len__(self):
251 return len(self._children)
252
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000253 def __bool__(self):
254 warnings.warn(
255 "The behavior of this method will change in future versions. "
256 "Use specific 'len(elem)' or 'elem is not None' test instead.",
257 FutureWarning, stacklevel=2
258 )
259 return len(self._children) != 0 # emulate old behaviour, for now
260
Armin Rigo9ed73062005-12-14 18:10:45 +0000261 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000262 # Returns the given subelement, by index.
Armin Rigo9ed73062005-12-14 18:10:45 +0000263 #
264 # @param index What subelement to return.
265 # @return The given subelement.
266 # @exception IndexError If the given element does not exist.
267
268 def __getitem__(self, index):
269 return self._children[index]
270
271 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000272 # Replaces the given subelement, by index.
Armin Rigo9ed73062005-12-14 18:10:45 +0000273 #
274 # @param index What subelement to replace.
275 # @param element The new element value.
276 # @exception IndexError If the given element does not exist.
Armin Rigo9ed73062005-12-14 18:10:45 +0000277
278 def __setitem__(self, index, element):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000279 # if isinstance(index, slice):
280 # for elt in element:
281 # assert iselement(elt)
282 # else:
283 # assert iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000284 self._children[index] = element
285
286 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000287 # Deletes the given subelement, by index.
Armin Rigo9ed73062005-12-14 18:10:45 +0000288 #
289 # @param index What subelement to delete.
290 # @exception IndexError If the given element does not exist.
291
292 def __delitem__(self, index):
293 del self._children[index]
294
295 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000296 # Adds a subelement to the end of this element. In document order,
297 # the new element will appear after the last existing subelement (or
298 # directly after the text, if it's the first subelement), but before
299 # the end tag for this element.
Armin Rigo9ed73062005-12-14 18:10:45 +0000300 #
301 # @param element The element to add.
Armin Rigo9ed73062005-12-14 18:10:45 +0000302
303 def append(self, element):
Eli Bendersky396e8fc2012-03-23 14:24:20 +0200304 self._assert_is_element(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000305 self._children.append(element)
306
307 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000308 # Appends subelements from a sequence.
309 #
310 # @param elements A sequence object with zero or more elements.
311 # @since 1.3
312
313 def extend(self, elements):
Eli Bendersky396e8fc2012-03-23 14:24:20 +0200314 for element in elements:
315 self._assert_is_element(element)
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000316 self._children.extend(elements)
317
318 ##
Armin Rigo9ed73062005-12-14 18:10:45 +0000319 # Inserts a subelement at the given position in this element.
320 #
321 # @param index Where to insert the new subelement.
Armin Rigo9ed73062005-12-14 18:10:45 +0000322
323 def insert(self, index, element):
Eli Bendersky396e8fc2012-03-23 14:24:20 +0200324 self._assert_is_element(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000325 self._children.insert(index, element)
326
Eli Bendersky396e8fc2012-03-23 14:24:20 +0200327 def _assert_is_element(self, e):
328 if not isinstance(e, Element):
329 raise TypeError('expected an Element, not %s' % type(e).__name__)
330
Armin Rigo9ed73062005-12-14 18:10:45 +0000331 ##
332 # Removes a matching subelement. Unlike the <b>find</b> methods,
333 # this method compares elements based on identity, not on tag
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000334 # value or contents. To remove subelements by other means, the
335 # easiest way is often to use a list comprehension to select what
336 # elements to keep, and use slice assignment to update the parent
337 # element.
Armin Rigo9ed73062005-12-14 18:10:45 +0000338 #
339 # @param element What element to remove.
340 # @exception ValueError If a matching element could not be found.
Armin Rigo9ed73062005-12-14 18:10:45 +0000341
342 def remove(self, element):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000343 # assert iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000344 self._children.remove(element)
345
346 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000347 # (Deprecated) Returns all subelements. The elements are returned
348 # in document order.
Armin Rigo9ed73062005-12-14 18:10:45 +0000349 #
350 # @return A list of subelements.
351 # @defreturn list of Element instances
352
353 def getchildren(self):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000354 warnings.warn(
355 "This method will be removed in future versions. "
356 "Use 'list(elem)' or iteration over elem instead.",
357 DeprecationWarning, stacklevel=2
358 )
Armin Rigo9ed73062005-12-14 18:10:45 +0000359 return self._children
360
361 ##
362 # Finds the first matching subelement, by tag name or path.
363 #
364 # @param path What element to look for.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000365 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000366 # @return The first matching element, or None if no element was found.
367 # @defreturn Element or None
368
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000369 def find(self, path, namespaces=None):
370 return ElementPath.find(self, path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000371
372 ##
373 # Finds text for the first matching subelement, by tag name or path.
374 #
375 # @param path What element to look for.
376 # @param default What to return if the element was not found.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000377 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000378 # @return The text content of the first matching element, or the
379 # default value no element was found. Note that if the element
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000380 # is found, but has no text content, this method returns an
Armin Rigo9ed73062005-12-14 18:10:45 +0000381 # empty string.
382 # @defreturn string
383
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000384 def findtext(self, path, default=None, namespaces=None):
385 return ElementPath.findtext(self, path, default, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000386
387 ##
388 # Finds all matching subelements, by tag name or path.
389 #
390 # @param path What element to look for.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000391 # @keyparam namespaces Optional namespace prefix map.
392 # @return A list or other sequence containing all matching elements,
Armin Rigo9ed73062005-12-14 18:10:45 +0000393 # in document order.
394 # @defreturn list of Element instances
395
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000396 def findall(self, path, namespaces=None):
397 return ElementPath.findall(self, path, namespaces)
398
399 ##
400 # Finds all matching subelements, by tag name or path.
401 #
402 # @param path What element to look for.
403 # @keyparam namespaces Optional namespace prefix map.
404 # @return An iterator or sequence containing all matching elements,
405 # in document order.
406 # @defreturn a generated sequence of Element instances
407
408 def iterfind(self, path, namespaces=None):
409 return ElementPath.iterfind(self, path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000410
411 ##
412 # Resets an element. This function removes all subelements, clears
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000413 # all attributes, and sets the <b>text</b> and <b>tail</b> attributes
414 # to None.
Armin Rigo9ed73062005-12-14 18:10:45 +0000415
416 def clear(self):
417 self.attrib.clear()
418 self._children = []
419 self.text = self.tail = None
420
421 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000422 # Gets an element attribute. Equivalent to <b>attrib.get</b>, but
423 # some implementations may handle this a bit more efficiently.
Armin Rigo9ed73062005-12-14 18:10:45 +0000424 #
425 # @param key What attribute to look for.
426 # @param default What to return if the attribute was not found.
427 # @return The attribute value, or the default value, if the
428 # attribute was not found.
429 # @defreturn string or None
430
431 def get(self, key, default=None):
432 return self.attrib.get(key, default)
433
434 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000435 # Sets an element attribute. Equivalent to <b>attrib[key] = value</b>,
436 # but some implementations may handle this a bit more efficiently.
Armin Rigo9ed73062005-12-14 18:10:45 +0000437 #
438 # @param key What attribute to set.
439 # @param value The attribute value.
440
441 def set(self, key, value):
442 self.attrib[key] = value
443
444 ##
445 # Gets a list of attribute names. The names are returned in an
446 # arbitrary order (just like for an ordinary Python dictionary).
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000447 # Equivalent to <b>attrib.keys()</b>.
Armin Rigo9ed73062005-12-14 18:10:45 +0000448 #
449 # @return A list of element attribute names.
450 # @defreturn list of strings
451
452 def keys(self):
453 return self.attrib.keys()
454
455 ##
456 # Gets element attributes, as a sequence. The attributes are
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000457 # returned in an arbitrary order. Equivalent to <b>attrib.items()</b>.
Armin Rigo9ed73062005-12-14 18:10:45 +0000458 #
459 # @return A list of (name, value) tuples for all attributes.
460 # @defreturn list of (string, string) tuples
461
462 def items(self):
463 return self.attrib.items()
464
465 ##
466 # Creates a tree iterator. The iterator loops over this element
467 # and all subelements, in document order, and returns all elements
468 # with a matching tag.
469 # <p>
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000470 # If the tree structure is modified during iteration, new or removed
471 # elements may or may not be included. To get a stable set, use the
472 # list() function on the iterator, and loop over the resulting list.
Armin Rigo9ed73062005-12-14 18:10:45 +0000473 #
474 # @param tag What tags to look for (default is to return all elements).
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000475 # @return An iterator containing all the matching elements.
476 # @defreturn iterator
Armin Rigo9ed73062005-12-14 18:10:45 +0000477
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000478 def iter(self, tag=None):
Armin Rigo9ed73062005-12-14 18:10:45 +0000479 if tag == "*":
480 tag = None
481 if tag is None or self.tag == tag:
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000482 yield self
483 for e in self._children:
484 for e in e.iter(tag):
485 yield e
486
487 # compatibility
488 def getiterator(self, tag=None):
489 # Change for a DeprecationWarning in 1.4
490 warnings.warn(
491 "This method will be removed in future versions. "
492 "Use 'elem.iter()' or 'list(elem.iter())' instead.",
493 PendingDeprecationWarning, stacklevel=2
494 )
495 return list(self.iter(tag))
496
497 ##
498 # Creates a text iterator. The iterator loops over this element
499 # and all subelements, in document order, and returns all inner
500 # text.
501 #
502 # @return An iterator containing all inner text.
503 # @defreturn iterator
504
505 def itertext(self):
506 tag = self.tag
507 if not isinstance(tag, str) and tag is not None:
508 return
509 if self.text:
510 yield self.text
511 for e in self:
512 for s in e.itertext():
513 yield s
514 if e.tail:
515 yield e.tail
Armin Rigo9ed73062005-12-14 18:10:45 +0000516
517# compatibility
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000518_Element = _ElementInterface = Element
Armin Rigo9ed73062005-12-14 18:10:45 +0000519
520##
521# Subelement factory. This function creates an element instance, and
522# appends it to an existing element.
523# <p>
524# The element name, attribute names, and attribute values can be
525# either 8-bit ASCII strings or Unicode strings.
526#
527# @param parent The parent element.
528# @param tag The subelement name.
529# @param attrib An optional dictionary, containing element attributes.
530# @param **extra Additional attributes, given as keyword arguments.
531# @return An element instance.
532# @defreturn Element
533
534def SubElement(parent, tag, attrib={}, **extra):
535 attrib = attrib.copy()
536 attrib.update(extra)
537 element = parent.makeelement(tag, attrib)
538 parent.append(element)
539 return element
540
541##
542# Comment element factory. This factory function creates a special
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000543# element that will be serialized as an XML comment by the standard
544# serializer.
Armin Rigo9ed73062005-12-14 18:10:45 +0000545# <p>
546# The comment string can be either an 8-bit ASCII string or a Unicode
547# string.
548#
549# @param text A string containing the comment string.
550# @return An element instance, representing a comment.
551# @defreturn Element
552
553def Comment(text=None):
554 element = Element(Comment)
555 element.text = text
556 return element
557
558##
559# PI element factory. This factory function creates a special element
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000560# that will be serialized as an XML processing instruction by the standard
561# serializer.
Armin Rigo9ed73062005-12-14 18:10:45 +0000562#
563# @param target A string containing the PI target.
564# @param text A string containing the PI contents, if any.
565# @return An element instance, representing a PI.
566# @defreturn Element
567
568def ProcessingInstruction(target, text=None):
569 element = Element(ProcessingInstruction)
570 element.text = target
571 if text:
572 element.text = element.text + " " + text
573 return element
574
575PI = ProcessingInstruction
576
577##
578# QName wrapper. This can be used to wrap a QName attribute value, in
579# order to get proper namespace handling on output.
580#
581# @param text A string containing the QName value, in the form {uri}local,
582# or, if the tag argument is given, the URI part of a QName.
583# @param tag Optional tag. If given, the first argument is interpreted as
584# an URI, and this argument is interpreted as a local name.
585# @return An opaque object, representing the QName.
586
587class QName:
588 def __init__(self, text_or_uri, tag=None):
589 if tag:
590 text_or_uri = "{%s}%s" % (text_or_uri, tag)
591 self.text = text_or_uri
592 def __str__(self):
593 return self.text
Georg Brandlb56c0e22010-12-09 18:10:27 +0000594 def __repr__(self):
Georg Brandlc95c9182010-12-09 18:26:02 +0000595 return '<QName %r>' % (self.text,)
Armin Rigo9ed73062005-12-14 18:10:45 +0000596 def __hash__(self):
597 return hash(self.text)
Mark Dickinsona56c4672009-01-27 18:17:45 +0000598 def __le__(self, other):
Armin Rigo9ed73062005-12-14 18:10:45 +0000599 if isinstance(other, QName):
Mark Dickinsona56c4672009-01-27 18:17:45 +0000600 return self.text <= other.text
601 return self.text <= other
602 def __lt__(self, other):
603 if isinstance(other, QName):
604 return self.text < other.text
605 return self.text < other
606 def __ge__(self, other):
607 if isinstance(other, QName):
608 return self.text >= other.text
609 return self.text >= other
610 def __gt__(self, other):
611 if isinstance(other, QName):
612 return self.text > other.text
613 return self.text > other
614 def __eq__(self, other):
615 if isinstance(other, QName):
616 return self.text == other.text
617 return self.text == other
618 def __ne__(self, other):
619 if isinstance(other, QName):
620 return self.text != other.text
621 return self.text != other
Armin Rigo9ed73062005-12-14 18:10:45 +0000622
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000623# --------------------------------------------------------------------
624
Armin Rigo9ed73062005-12-14 18:10:45 +0000625##
626# ElementTree wrapper class. This class represents an entire element
627# hierarchy, and adds some extra support for serialization to and from
628# standard XML.
629#
630# @param element Optional root element.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000631# @keyparam file Optional file handle or file name. If given, the
Armin Rigo9ed73062005-12-14 18:10:45 +0000632# tree is initialized with the contents of this XML file.
633
634class ElementTree:
635
636 def __init__(self, element=None, file=None):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000637 # assert element is None or iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000638 self._root = element # first node
639 if file:
640 self.parse(file)
641
642 ##
643 # Gets the root element for this tree.
644 #
645 # @return An element instance.
646 # @defreturn Element
647
648 def getroot(self):
649 return self._root
650
651 ##
652 # Replaces the root element for this tree. This discards the
653 # current contents of the tree, and replaces it with the given
654 # element. Use with care.
655 #
656 # @param element An element instance.
657
658 def _setroot(self, element):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000659 # assert iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000660 self._root = element
661
662 ##
663 # Loads an external XML document into this element tree.
664 #
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000665 # @param source A file name or file object. If a file object is
666 # given, it only has to implement a <b>read(n)</b> method.
667 # @keyparam parser An optional parser instance. If not given, the
668 # standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +0000669 # @return The document root element.
670 # @defreturn Element
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000671 # @exception ParseError If the parser fails to parse the document.
Armin Rigo9ed73062005-12-14 18:10:45 +0000672
673 def parse(self, source, parser=None):
Antoine Pitroue033e062010-10-29 10:38:18 +0000674 close_source = False
Armin Rigo9ed73062005-12-14 18:10:45 +0000675 if not hasattr(source, "read"):
676 source = open(source, "rb")
Antoine Pitroue033e062010-10-29 10:38:18 +0000677 close_source = True
678 try:
679 if not parser:
680 parser = XMLParser(target=TreeBuilder())
681 while 1:
682 data = source.read(65536)
683 if not data:
684 break
685 parser.feed(data)
686 self._root = parser.close()
687 return self._root
688 finally:
689 if close_source:
690 source.close()
Armin Rigo9ed73062005-12-14 18:10:45 +0000691
692 ##
693 # Creates a tree iterator for the root element. The iterator loops
694 # over all elements in this tree, in document order.
695 #
696 # @param tag What tags to look for (default is to return all elements)
697 # @return An iterator.
698 # @defreturn iterator
699
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000700 def iter(self, tag=None):
701 # assert self._root is not None
702 return self._root.iter(tag)
703
704 # compatibility
Armin Rigo9ed73062005-12-14 18:10:45 +0000705 def getiterator(self, tag=None):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000706 # Change for a DeprecationWarning in 1.4
707 warnings.warn(
708 "This method will be removed in future versions. "
709 "Use 'tree.iter()' or 'list(tree.iter())' instead.",
710 PendingDeprecationWarning, stacklevel=2
711 )
712 return list(self.iter(tag))
Armin Rigo9ed73062005-12-14 18:10:45 +0000713
714 ##
715 # Finds the first toplevel element with given tag.
716 # Same as getroot().find(path).
717 #
718 # @param path What element to look for.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000719 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000720 # @return The first matching element, or None if no element was found.
721 # @defreturn Element or None
722
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000723 def find(self, path, namespaces=None):
724 # assert self._root is not None
Armin Rigo9ed73062005-12-14 18:10:45 +0000725 if path[:1] == "/":
726 path = "." + path
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000727 warnings.warn(
728 "This search is broken in 1.3 and earlier, and will be "
729 "fixed in a future version. If you rely on the current "
730 "behaviour, change it to %r" % path,
731 FutureWarning, stacklevel=2
732 )
733 return self._root.find(path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000734
735 ##
736 # Finds the element text for the first toplevel element with given
737 # tag. Same as getroot().findtext(path).
738 #
739 # @param path What toplevel element to look for.
740 # @param default What to return if the element was not found.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000741 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000742 # @return The text content of the first matching element, or the
743 # default value no element was found. Note that if the element
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000744 # is found, but has no text content, this method returns an
Armin Rigo9ed73062005-12-14 18:10:45 +0000745 # empty string.
746 # @defreturn string
747
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000748 def findtext(self, path, default=None, namespaces=None):
749 # assert self._root is not None
Armin Rigo9ed73062005-12-14 18:10:45 +0000750 if path[:1] == "/":
751 path = "." + path
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000752 warnings.warn(
753 "This search is broken in 1.3 and earlier, and will be "
754 "fixed in a future version. If you rely on the current "
755 "behaviour, change it to %r" % path,
756 FutureWarning, stacklevel=2
757 )
758 return self._root.findtext(path, default, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000759
760 ##
761 # Finds all toplevel elements with the given tag.
762 # Same as getroot().findall(path).
763 #
764 # @param path What element to look for.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000765 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000766 # @return A list or iterator containing all matching elements,
767 # in document order.
768 # @defreturn list of Element instances
769
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000770 def findall(self, path, namespaces=None):
771 # assert self._root is not None
Armin Rigo9ed73062005-12-14 18:10:45 +0000772 if path[:1] == "/":
773 path = "." + path
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000774 warnings.warn(
775 "This search is broken in 1.3 and earlier, and will be "
776 "fixed in a future version. If you rely on the current "
777 "behaviour, change it to %r" % path,
778 FutureWarning, stacklevel=2
779 )
780 return self._root.findall(path, namespaces)
781
782 ##
783 # Finds all matching subelements, by tag name or path.
784 # Same as getroot().iterfind(path).
785 #
786 # @param path What element to look for.
787 # @keyparam namespaces Optional namespace prefix map.
788 # @return An iterator or sequence containing all matching elements,
789 # in document order.
790 # @defreturn a generated sequence of Element instances
791
792 def iterfind(self, path, namespaces=None):
793 # assert self._root is not None
794 if path[:1] == "/":
795 path = "." + path
796 warnings.warn(
797 "This search is broken in 1.3 and earlier, and will be "
798 "fixed in a future version. If you rely on the current "
799 "behaviour, change it to %r" % path,
800 FutureWarning, stacklevel=2
801 )
802 return self._root.iterfind(path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000803
804 ##
805 # Writes the element tree to a file, as XML.
806 #
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000807 # @def write(file, **options)
Armin Rigo9ed73062005-12-14 18:10:45 +0000808 # @param file A file name, or a file object opened for writing.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000809 # @param **options Options, given as keyword arguments.
Florent Xiclunac17f1722010-08-08 19:48:29 +0000810 # @keyparam encoding Optional output encoding (default is US-ASCII).
811 # Use "unicode" to return a Unicode string.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000812 # @keyparam method Optional output method ("xml", "html", "text" or
813 # "c14n"; default is "xml").
814 # @keyparam xml_declaration Controls if an XML declaration should
815 # be added to the file. Use False for never, True for always,
Florent Xiclunac17f1722010-08-08 19:48:29 +0000816 # None for only if not US-ASCII or UTF-8 or Unicode. None is default.
Armin Rigo9ed73062005-12-14 18:10:45 +0000817
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000818 def write(self, file_or_filename,
819 # keyword arguments
820 encoding=None,
821 xml_declaration=None,
822 default_namespace=None,
823 method=None):
824 # assert self._root is not None
825 if not method:
826 method = "xml"
827 elif method not in _serialize:
828 # FIXME: raise an ImportError for c14n if ElementC14N is missing?
829 raise ValueError("unknown method %r" % method)
Florent Xiclunac17f1722010-08-08 19:48:29 +0000830 if not encoding:
831 if method == "c14n":
832 encoding = "utf-8"
833 else:
834 encoding = "us-ascii"
835 elif encoding == str: # lxml.etree compatibility.
836 encoding = "unicode"
837 else:
838 encoding = encoding.lower()
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000839 if hasattr(file_or_filename, "write"):
840 file = file_or_filename
Armin Rigo9ed73062005-12-14 18:10:45 +0000841 else:
Florent Xiclunac17f1722010-08-08 19:48:29 +0000842 if encoding != "unicode":
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000843 file = open(file_or_filename, "wb")
Armin Rigo9ed73062005-12-14 18:10:45 +0000844 else:
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000845 file = open(file_or_filename, "w")
Florent Xiclunac17f1722010-08-08 19:48:29 +0000846 if encoding != "unicode":
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000847 def write(text):
848 try:
849 return file.write(text.encode(encoding,
850 "xmlcharrefreplace"))
851 except (TypeError, AttributeError):
852 _raise_serialization_error(text)
853 else:
854 write = file.write
Florent Xiclunac17f1722010-08-08 19:48:29 +0000855 if method == "xml" and (xml_declaration or
856 (xml_declaration is None and
857 encoding not in ("utf-8", "us-ascii", "unicode"))):
858 declared_encoding = encoding
859 if encoding == "unicode":
860 # Retrieve the default encoding for the xml declaration
861 import locale
862 declared_encoding = locale.getpreferredencoding()
863 write("<?xml version='1.0' encoding='%s'?>\n" % declared_encoding)
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000864 if method == "text":
865 _serialize_text(write, self._root)
866 else:
867 qnames, namespaces = _namespaces(self._root, default_namespace)
868 serialize = _serialize[method]
869 serialize(write, self._root, qnames, namespaces)
870 if file_or_filename is not file:
871 file.close()
872
873 def write_c14n(self, file):
874 # lxml.etree compatibility. use output method instead
875 return self.write(file, method="c14n")
Armin Rigo9ed73062005-12-14 18:10:45 +0000876
877# --------------------------------------------------------------------
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000878# serialization support
879
880def _namespaces(elem, default_namespace=None):
881 # identify namespaces used in this tree
882
883 # maps qnames to *encoded* prefix:local names
884 qnames = {None: None}
885
886 # maps uri:s to prefixes
887 namespaces = {}
888 if default_namespace:
889 namespaces[default_namespace] = ""
890
891 def add_qname(qname):
892 # calculate serialized qname representation
893 try:
894 if qname[:1] == "{":
895 uri, tag = qname[1:].rsplit("}", 1)
896 prefix = namespaces.get(uri)
897 if prefix is None:
898 prefix = _namespace_map.get(uri)
899 if prefix is None:
900 prefix = "ns%d" % len(namespaces)
901 if prefix != "xml":
902 namespaces[uri] = prefix
903 if prefix:
904 qnames[qname] = "%s:%s" % (prefix, tag)
905 else:
906 qnames[qname] = tag # default element
907 else:
908 if default_namespace:
909 # FIXME: can this be handled in XML 1.0?
910 raise ValueError(
911 "cannot use non-qualified names with "
912 "default_namespace option"
913 )
914 qnames[qname] = qname
915 except TypeError:
916 _raise_serialization_error(qname)
917
918 # populate qname and namespaces table
919 try:
920 iterate = elem.iter
921 except AttributeError:
922 iterate = elem.getiterator # cET compatibility
923 for elem in iterate():
924 tag = elem.tag
Senthil Kumaranec30b3d2010-11-09 02:36:59 +0000925 if isinstance(tag, QName):
926 if tag.text not in qnames:
927 add_qname(tag.text)
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000928 elif isinstance(tag, str):
929 if tag not in qnames:
930 add_qname(tag)
931 elif tag is not None and tag is not Comment and tag is not PI:
932 _raise_serialization_error(tag)
933 for key, value in elem.items():
934 if isinstance(key, QName):
935 key = key.text
936 if key not in qnames:
937 add_qname(key)
938 if isinstance(value, QName) and value.text not in qnames:
939 add_qname(value.text)
940 text = elem.text
941 if isinstance(text, QName) and text.text not in qnames:
942 add_qname(text.text)
943 return qnames, namespaces
944
945def _serialize_xml(write, elem, qnames, namespaces):
946 tag = elem.tag
947 text = elem.text
948 if tag is Comment:
949 write("<!--%s-->" % text)
950 elif tag is ProcessingInstruction:
951 write("<?%s?>" % text)
952 else:
953 tag = qnames[tag]
954 if tag is None:
955 if text:
956 write(_escape_cdata(text))
957 for e in elem:
958 _serialize_xml(write, e, qnames, None)
959 else:
960 write("<" + tag)
961 items = list(elem.items())
962 if items or namespaces:
963 if namespaces:
964 for v, k in sorted(namespaces.items(),
965 key=lambda x: x[1]): # sort on prefix
966 if k:
967 k = ":" + k
968 write(" xmlns%s=\"%s\"" % (
969 k,
970 _escape_attrib(v)
971 ))
972 for k, v in sorted(items): # lexical order
973 if isinstance(k, QName):
974 k = k.text
975 if isinstance(v, QName):
976 v = qnames[v.text]
977 else:
978 v = _escape_attrib(v)
979 write(" %s=\"%s\"" % (qnames[k], v))
980 if text or len(elem):
981 write(">")
982 if text:
983 write(_escape_cdata(text))
984 for e in elem:
985 _serialize_xml(write, e, qnames, None)
986 write("</" + tag + ">")
987 else:
988 write(" />")
989 if elem.tail:
990 write(_escape_cdata(elem.tail))
991
992HTML_EMPTY = ("area", "base", "basefont", "br", "col", "frame", "hr",
993 "img", "input", "isindex", "link", "meta" "param")
994
995try:
996 HTML_EMPTY = set(HTML_EMPTY)
997except NameError:
998 pass
999
1000def _serialize_html(write, elem, qnames, namespaces):
1001 tag = elem.tag
1002 text = elem.text
1003 if tag is Comment:
1004 write("<!--%s-->" % _escape_cdata(text))
1005 elif tag is ProcessingInstruction:
1006 write("<?%s?>" % _escape_cdata(text))
1007 else:
1008 tag = qnames[tag]
1009 if tag is None:
1010 if text:
1011 write(_escape_cdata(text))
1012 for e in elem:
1013 _serialize_html(write, e, qnames, None)
1014 else:
1015 write("<" + tag)
1016 items = list(elem.items())
1017 if items or namespaces:
1018 if namespaces:
1019 for v, k in sorted(namespaces.items(),
1020 key=lambda x: x[1]): # sort on prefix
1021 if k:
1022 k = ":" + k
1023 write(" xmlns%s=\"%s\"" % (
1024 k,
1025 _escape_attrib(v)
1026 ))
1027 for k, v in sorted(items): # lexical order
1028 if isinstance(k, QName):
1029 k = k.text
1030 if isinstance(v, QName):
1031 v = qnames[v.text]
1032 else:
1033 v = _escape_attrib_html(v)
1034 # FIXME: handle boolean attributes
1035 write(" %s=\"%s\"" % (qnames[k], v))
1036 write(">")
1037 tag = tag.lower()
1038 if text:
1039 if tag == "script" or tag == "style":
1040 write(text)
1041 else:
1042 write(_escape_cdata(text))
1043 for e in elem:
1044 _serialize_html(write, e, qnames, None)
1045 if tag not in HTML_EMPTY:
1046 write("</" + tag + ">")
1047 if elem.tail:
1048 write(_escape_cdata(elem.tail))
1049
1050def _serialize_text(write, elem):
1051 for part in elem.itertext():
1052 write(part)
1053 if elem.tail:
1054 write(elem.tail)
1055
1056_serialize = {
1057 "xml": _serialize_xml,
1058 "html": _serialize_html,
1059 "text": _serialize_text,
1060# this optional method is imported at the end of the module
1061# "c14n": _serialize_c14n,
1062}
Armin Rigo9ed73062005-12-14 18:10:45 +00001063
1064##
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001065# Registers a namespace prefix. The registry is global, and any
1066# existing mapping for either the given prefix or the namespace URI
1067# will be removed.
Armin Rigo9ed73062005-12-14 18:10:45 +00001068#
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001069# @param prefix Namespace prefix.
1070# @param uri Namespace uri. Tags and attributes in this namespace
1071# will be serialized with the given prefix, if at all possible.
1072# @exception ValueError If the prefix is reserved, or is otherwise
1073# invalid.
Armin Rigo9ed73062005-12-14 18:10:45 +00001074
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001075def register_namespace(prefix, uri):
1076 if re.match("ns\d+$", prefix):
1077 raise ValueError("Prefix format reserved for internal use")
Georg Brandl90b20672010-12-28 10:38:33 +00001078 for k, v in list(_namespace_map.items()):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001079 if k == uri or v == prefix:
1080 del _namespace_map[k]
1081 _namespace_map[uri] = prefix
1082
1083_namespace_map = {
1084 # "well-known" namespace prefixes
1085 "http://www.w3.org/XML/1998/namespace": "xml",
1086 "http://www.w3.org/1999/xhtml": "html",
1087 "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
1088 "http://schemas.xmlsoap.org/wsdl/": "wsdl",
1089 # xml schema
1090 "http://www.w3.org/2001/XMLSchema": "xs",
1091 "http://www.w3.org/2001/XMLSchema-instance": "xsi",
1092 # dublin core
1093 "http://purl.org/dc/elements/1.1/": "dc",
1094}
Florent Xicluna16395052012-02-16 23:28:35 +01001095# For tests and troubleshooting
1096register_namespace._namespace_map = _namespace_map
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001097
1098def _raise_serialization_error(text):
1099 raise TypeError(
1100 "cannot serialize %r (type %s)" % (text, type(text).__name__)
1101 )
1102
1103def _escape_cdata(text):
1104 # escape character data
1105 try:
1106 # it's worth avoiding do-nothing calls for strings that are
1107 # shorter than 500 character, or so. assume that's, by far,
1108 # the most common case in most applications.
1109 if "&" in text:
1110 text = text.replace("&", "&amp;")
1111 if "<" in text:
1112 text = text.replace("<", "&lt;")
1113 if ">" in text:
1114 text = text.replace(">", "&gt;")
1115 return text
1116 except (TypeError, AttributeError):
1117 _raise_serialization_error(text)
1118
1119def _escape_attrib(text):
1120 # escape attribute value
1121 try:
1122 if "&" in text:
1123 text = text.replace("&", "&amp;")
1124 if "<" in text:
1125 text = text.replace("<", "&lt;")
1126 if ">" in text:
1127 text = text.replace(">", "&gt;")
1128 if "\"" in text:
1129 text = text.replace("\"", "&quot;")
1130 if "\n" in text:
1131 text = text.replace("\n", "&#10;")
1132 return text
1133 except (TypeError, AttributeError):
1134 _raise_serialization_error(text)
1135
1136def _escape_attrib_html(text):
1137 # escape attribute value
1138 try:
1139 if "&" in text:
1140 text = text.replace("&", "&amp;")
1141 if ">" in text:
1142 text = text.replace(">", "&gt;")
1143 if "\"" in text:
1144 text = text.replace("\"", "&quot;")
1145 return text
1146 except (TypeError, AttributeError):
1147 _raise_serialization_error(text)
1148
1149# --------------------------------------------------------------------
1150
1151##
1152# Generates a string representation of an XML element, including all
Florent Xiclunac17f1722010-08-08 19:48:29 +00001153# subelements. If encoding is "unicode", the return type is a string;
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001154# otherwise it is a bytes array.
1155#
1156# @param element An Element instance.
Florent Xiclunac17f1722010-08-08 19:48:29 +00001157# @keyparam encoding Optional output encoding (default is US-ASCII).
1158# Use "unicode" to return a Unicode string.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001159# @keyparam method Optional output method ("xml", "html", "text" or
1160# "c14n"; default is "xml").
1161# @return An (optionally) encoded string containing the XML data.
1162# @defreturn string
1163
1164def tostring(element, encoding=None, method=None):
1165 class dummy:
1166 pass
1167 data = []
1168 file = dummy()
1169 file.write = data.append
1170 ElementTree(element).write(file, encoding, method=method)
Florent Xiclunac17f1722010-08-08 19:48:29 +00001171 if encoding in (str, "unicode"):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001172 return "".join(data)
Florent Xiclunac17f1722010-08-08 19:48:29 +00001173 else:
1174 return b"".join(data)
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001175
1176##
1177# Generates a string representation of an XML element, including all
Florent Xiclunac17f1722010-08-08 19:48:29 +00001178# subelements. If encoding is False, the string is returned as a
1179# sequence of string fragments; otherwise it is a sequence of
1180# bytestrings.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001181#
1182# @param element An Element instance.
1183# @keyparam encoding Optional output encoding (default is US-ASCII).
Florent Xiclunac17f1722010-08-08 19:48:29 +00001184# Use "unicode" to return a Unicode string.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001185# @keyparam method Optional output method ("xml", "html", "text" or
1186# "c14n"; default is "xml").
1187# @return A sequence object containing the XML data.
1188# @defreturn sequence
1189# @since 1.3
1190
1191def tostringlist(element, encoding=None, method=None):
1192 class dummy:
1193 pass
1194 data = []
1195 file = dummy()
1196 file.write = data.append
1197 ElementTree(element).write(file, encoding, method=method)
1198 # FIXME: merge small fragments into larger parts
1199 return data
Armin Rigo9ed73062005-12-14 18:10:45 +00001200
1201##
1202# Writes an element tree or element structure to sys.stdout. This
1203# function should be used for debugging only.
1204# <p>
1205# The exact output format is implementation dependent. In this
1206# version, it's written as an ordinary XML file.
1207#
1208# @param elem An element tree or an individual element.
1209
1210def dump(elem):
1211 # debugging
1212 if not isinstance(elem, ElementTree):
1213 elem = ElementTree(elem)
Florent Xiclunac17f1722010-08-08 19:48:29 +00001214 elem.write(sys.stdout, encoding="unicode")
Armin Rigo9ed73062005-12-14 18:10:45 +00001215 tail = elem.getroot().tail
1216 if not tail or tail[-1] != "\n":
1217 sys.stdout.write("\n")
1218
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001219# --------------------------------------------------------------------
1220# parsing
Armin Rigo9ed73062005-12-14 18:10:45 +00001221
1222##
1223# Parses an XML document into an element tree.
1224#
1225# @param source A filename or file object containing XML data.
1226# @param parser An optional parser instance. If not given, the
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001227# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001228# @return An ElementTree instance
1229
1230def parse(source, parser=None):
1231 tree = ElementTree()
1232 tree.parse(source, parser)
1233 return tree
1234
1235##
1236# Parses an XML document into an element tree incrementally, and reports
1237# what's going on to the user.
1238#
1239# @param source A filename or file object containing XML data.
1240# @param events A list of events to report back. If omitted, only "end"
1241# events are reported.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001242# @param parser An optional parser instance. If not given, the
1243# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001244# @return A (event, elem) iterator.
1245
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001246def iterparse(source, events=None, parser=None):
Antoine Pitroue033e062010-10-29 10:38:18 +00001247 close_source = False
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001248 if not hasattr(source, "read"):
1249 source = open(source, "rb")
Antoine Pitroue033e062010-10-29 10:38:18 +00001250 close_source = True
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001251 if not parser:
1252 parser = XMLParser(target=TreeBuilder())
Antoine Pitroue033e062010-10-29 10:38:18 +00001253 return _IterParseIterator(source, events, parser, close_source)
Armin Rigo9ed73062005-12-14 18:10:45 +00001254
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001255class _IterParseIterator:
1256
Antoine Pitroue033e062010-10-29 10:38:18 +00001257 def __init__(self, source, events, parser, close_source=False):
Armin Rigo9ed73062005-12-14 18:10:45 +00001258 self._file = source
Antoine Pitroue033e062010-10-29 10:38:18 +00001259 self._close_file = close_source
Armin Rigo9ed73062005-12-14 18:10:45 +00001260 self._events = []
1261 self._index = 0
Florent Xicluna91d51932011-11-01 23:31:09 +01001262 self._error = None
Armin Rigo9ed73062005-12-14 18:10:45 +00001263 self.root = self._root = None
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001264 self._parser = parser
Armin Rigo9ed73062005-12-14 18:10:45 +00001265 # wire up the parser for event reporting
1266 parser = self._parser._parser
1267 append = self._events.append
1268 if events is None:
1269 events = ["end"]
1270 for event in events:
1271 if event == "start":
1272 try:
1273 parser.ordered_attributes = 1
1274 parser.specified_attributes = 1
1275 def handler(tag, attrib_in, event=event, append=append,
1276 start=self._parser._start_list):
1277 append((event, start(tag, attrib_in)))
1278 parser.StartElementHandler = handler
1279 except AttributeError:
1280 def handler(tag, attrib_in, event=event, append=append,
1281 start=self._parser._start):
1282 append((event, start(tag, attrib_in)))
1283 parser.StartElementHandler = handler
1284 elif event == "end":
1285 def handler(tag, event=event, append=append,
1286 end=self._parser._end):
1287 append((event, end(tag)))
1288 parser.EndElementHandler = handler
1289 elif event == "start-ns":
1290 def handler(prefix, uri, event=event, append=append):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001291 append((event, (prefix or "", uri or "")))
Armin Rigo9ed73062005-12-14 18:10:45 +00001292 parser.StartNamespaceDeclHandler = handler
1293 elif event == "end-ns":
1294 def handler(prefix, event=event, append=append):
1295 append((event, None))
1296 parser.EndNamespaceDeclHandler = handler
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001297 else:
1298 raise ValueError("unknown event %r" % event)
Armin Rigo9ed73062005-12-14 18:10:45 +00001299
Georg Brandla18af4e2007-04-21 15:47:16 +00001300 def __next__(self):
Armin Rigo9ed73062005-12-14 18:10:45 +00001301 while 1:
1302 try:
1303 item = self._events[self._index]
Florent Xicluna91d51932011-11-01 23:31:09 +01001304 self._index += 1
Armin Rigo9ed73062005-12-14 18:10:45 +00001305 return item
Florent Xicluna91d51932011-11-01 23:31:09 +01001306 except IndexError:
1307 pass
1308 if self._error:
1309 e = self._error
1310 self._error = None
1311 raise e
1312 if self._parser is None:
1313 self.root = self._root
1314 if self._close_file:
1315 self._file.close()
1316 raise StopIteration
1317 # load event buffer
1318 del self._events[:]
1319 self._index = 0
1320 data = self._file.read(16384)
1321 if data:
1322 try:
1323 self._parser.feed(data)
1324 except SyntaxError as exc:
1325 self._error = exc
1326 else:
1327 self._root = self._parser.close()
1328 self._parser = None
Armin Rigo9ed73062005-12-14 18:10:45 +00001329
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001330 def __iter__(self):
1331 return self
Armin Rigo9ed73062005-12-14 18:10:45 +00001332
1333##
1334# Parses an XML document from a string constant. This function can
1335# be used to embed "XML literals" in Python code.
1336#
1337# @param source A string containing XML data.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001338# @param parser An optional parser instance. If not given, the
1339# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001340# @return An Element instance.
1341# @defreturn Element
1342
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001343def XML(text, parser=None):
1344 if not parser:
1345 parser = XMLParser(target=TreeBuilder())
Armin Rigo9ed73062005-12-14 18:10:45 +00001346 parser.feed(text)
1347 return parser.close()
1348
1349##
1350# Parses an XML document from a string constant, and also returns
1351# a dictionary which maps from element id:s to elements.
1352#
1353# @param source A string containing XML data.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001354# @param parser An optional parser instance. If not given, the
1355# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001356# @return A tuple containing an Element instance and a dictionary.
1357# @defreturn (Element, dictionary)
1358
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001359def XMLID(text, parser=None):
1360 if not parser:
1361 parser = XMLParser(target=TreeBuilder())
Armin Rigo9ed73062005-12-14 18:10:45 +00001362 parser.feed(text)
1363 tree = parser.close()
1364 ids = {}
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001365 for elem in tree.iter():
Armin Rigo9ed73062005-12-14 18:10:45 +00001366 id = elem.get("id")
1367 if id:
1368 ids[id] = elem
1369 return tree, ids
1370
1371##
1372# Parses an XML document from a string constant. Same as {@link #XML}.
1373#
1374# @def fromstring(text)
1375# @param source A string containing XML data.
1376# @return An Element instance.
1377# @defreturn Element
1378
1379fromstring = XML
1380
1381##
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001382# Parses an XML document from a sequence of string fragments.
Armin Rigo9ed73062005-12-14 18:10:45 +00001383#
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001384# @param sequence A list or other sequence containing XML data fragments.
1385# @param parser An optional parser instance. If not given, the
1386# standard {@link XMLParser} parser is used.
1387# @return An Element instance.
1388# @defreturn Element
1389# @since 1.3
Armin Rigo9ed73062005-12-14 18:10:45 +00001390
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001391def fromstringlist(sequence, parser=None):
1392 if not parser:
1393 parser = XMLParser(target=TreeBuilder())
1394 for text in sequence:
1395 parser.feed(text)
1396 return parser.close()
1397
1398# --------------------------------------------------------------------
Armin Rigo9ed73062005-12-14 18:10:45 +00001399
1400##
1401# Generic element structure builder. This builder converts a sequence
1402# of {@link #TreeBuilder.start}, {@link #TreeBuilder.data}, and {@link
1403# #TreeBuilder.end} method calls to a well-formed element structure.
1404# <p>
1405# You can use this class to build an element structure using a custom XML
1406# parser, or a parser for some other XML-like format.
1407#
1408# @param element_factory Optional element factory. This factory
1409# is called to create new Element instances, as necessary.
1410
1411class TreeBuilder:
1412
1413 def __init__(self, element_factory=None):
1414 self._data = [] # data collector
1415 self._elem = [] # element stack
1416 self._last = None # last element
1417 self._tail = None # true if we're after an end tag
1418 if element_factory is None:
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001419 element_factory = Element
Armin Rigo9ed73062005-12-14 18:10:45 +00001420 self._factory = element_factory
1421
1422 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001423 # Flushes the builder buffers, and returns the toplevel document
Armin Rigo9ed73062005-12-14 18:10:45 +00001424 # element.
1425 #
1426 # @return An Element instance.
1427 # @defreturn Element
1428
1429 def close(self):
1430 assert len(self._elem) == 0, "missing end tags"
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001431 assert self._last is not None, "missing toplevel element"
Armin Rigo9ed73062005-12-14 18:10:45 +00001432 return self._last
1433
1434 def _flush(self):
1435 if self._data:
1436 if self._last is not None:
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001437 text = "".join(self._data)
Armin Rigo9ed73062005-12-14 18:10:45 +00001438 if self._tail:
1439 assert self._last.tail is None, "internal error (tail)"
1440 self._last.tail = text
1441 else:
1442 assert self._last.text is None, "internal error (text)"
1443 self._last.text = text
1444 self._data = []
1445
1446 ##
1447 # Adds text to the current element.
1448 #
1449 # @param data A string. This should be either an 8-bit string
1450 # containing ASCII text, or a Unicode string.
1451
1452 def data(self, data):
1453 self._data.append(data)
1454
1455 ##
1456 # Opens a new element.
1457 #
1458 # @param tag The element name.
1459 # @param attrib A dictionary containing element attributes.
1460 # @return The opened element.
1461 # @defreturn Element
1462
1463 def start(self, tag, attrs):
1464 self._flush()
1465 self._last = elem = self._factory(tag, attrs)
1466 if self._elem:
1467 self._elem[-1].append(elem)
1468 self._elem.append(elem)
1469 self._tail = 0
1470 return elem
1471
1472 ##
1473 # Closes the current element.
1474 #
1475 # @param tag The element name.
1476 # @return The closed element.
1477 # @defreturn Element
1478
1479 def end(self, tag):
1480 self._flush()
1481 self._last = self._elem.pop()
1482 assert self._last.tag == tag,\
1483 "end tag mismatch (expected %s, got %s)" % (
1484 self._last.tag, tag)
1485 self._tail = 1
1486 return self._last
1487
1488##
1489# Element structure builder for XML source data, based on the
1490# <b>expat</b> parser.
1491#
1492# @keyparam target Target object. If omitted, the builder uses an
1493# instance of the standard {@link #TreeBuilder} class.
1494# @keyparam html Predefine HTML entities. This flag is not supported
1495# by the current implementation.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001496# @keyparam encoding Optional encoding. If given, the value overrides
1497# the encoding specified in the XML file.
Armin Rigo9ed73062005-12-14 18:10:45 +00001498# @see #ElementTree
1499# @see #TreeBuilder
1500
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001501class XMLParser:
Armin Rigo9ed73062005-12-14 18:10:45 +00001502
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001503 def __init__(self, html=0, target=None, encoding=None):
Armin Rigo9ed73062005-12-14 18:10:45 +00001504 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001505 from xml.parsers import expat
Armin Rigo9ed73062005-12-14 18:10:45 +00001506 except ImportError:
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001507 try:
1508 import pyexpat as expat
1509 except ImportError:
1510 raise ImportError(
1511 "No module named expat; use SimpleXMLTreeBuilder instead"
1512 )
1513 parser = expat.ParserCreate(encoding, "}")
Armin Rigo9ed73062005-12-14 18:10:45 +00001514 if target is None:
1515 target = TreeBuilder()
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001516 # underscored names are provided for compatibility only
1517 self.parser = self._parser = parser
1518 self.target = self._target = target
1519 self._error = expat.error
Armin Rigo9ed73062005-12-14 18:10:45 +00001520 self._names = {} # name memo cache
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001521 # main callbacks
Armin Rigo9ed73062005-12-14 18:10:45 +00001522 parser.DefaultHandlerExpand = self._default
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001523 if hasattr(target, 'start'):
1524 parser.StartElementHandler = self._start
1525 if hasattr(target, 'end'):
1526 parser.EndElementHandler = self._end
1527 if hasattr(target, 'data'):
1528 parser.CharacterDataHandler = target.data
1529 # miscellaneous callbacks
1530 if hasattr(target, 'comment'):
1531 parser.CommentHandler = target.comment
1532 if hasattr(target, 'pi'):
1533 parser.ProcessingInstructionHandler = target.pi
Armin Rigo9ed73062005-12-14 18:10:45 +00001534 # let expat do the buffering, if supported
1535 try:
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001536 parser.buffer_text = 1
Armin Rigo9ed73062005-12-14 18:10:45 +00001537 except AttributeError:
1538 pass
1539 # use new-style attribute handling, if supported
1540 try:
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001541 parser.ordered_attributes = 1
1542 parser.specified_attributes = 1
1543 if hasattr(target, 'start'):
1544 parser.StartElementHandler = self._start_list
Armin Rigo9ed73062005-12-14 18:10:45 +00001545 except AttributeError:
1546 pass
Armin Rigo9ed73062005-12-14 18:10:45 +00001547 self._doctype = None
1548 self.entity = {}
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001549 try:
1550 self.version = "Expat %d.%d.%d" % expat.version_info
1551 except AttributeError:
1552 pass # unknown
1553
1554 def _raiseerror(self, value):
1555 err = ParseError(value)
1556 err.code = value.code
1557 err.position = value.lineno, value.offset
1558 raise err
Armin Rigo9ed73062005-12-14 18:10:45 +00001559
Armin Rigo9ed73062005-12-14 18:10:45 +00001560 def _fixname(self, key):
1561 # expand qname, and convert name string to ascii, if possible
1562 try:
1563 name = self._names[key]
1564 except KeyError:
1565 name = key
1566 if "}" in name:
1567 name = "{" + name
Martin v. Löwisf30bb0e2007-07-28 11:40:46 +00001568 self._names[key] = name
Armin Rigo9ed73062005-12-14 18:10:45 +00001569 return name
1570
1571 def _start(self, tag, attrib_in):
1572 fixname = self._fixname
1573 tag = fixname(tag)
1574 attrib = {}
1575 for key, value in attrib_in.items():
Martin v. Löwisf30bb0e2007-07-28 11:40:46 +00001576 attrib[fixname(key)] = value
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001577 return self.target.start(tag, attrib)
Armin Rigo9ed73062005-12-14 18:10:45 +00001578
1579 def _start_list(self, tag, attrib_in):
1580 fixname = self._fixname
1581 tag = fixname(tag)
1582 attrib = {}
1583 if attrib_in:
1584 for i in range(0, len(attrib_in), 2):
Martin v. Löwisf30bb0e2007-07-28 11:40:46 +00001585 attrib[fixname(attrib_in[i])] = attrib_in[i+1]
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001586 return self.target.start(tag, attrib)
Armin Rigo9ed73062005-12-14 18:10:45 +00001587
Armin Rigo9ed73062005-12-14 18:10:45 +00001588 def _end(self, tag):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001589 return self.target.end(self._fixname(tag))
1590
Armin Rigo9ed73062005-12-14 18:10:45 +00001591 def _default(self, text):
1592 prefix = text[:1]
1593 if prefix == "&":
1594 # deal with undefined entities
1595 try:
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001596 data_handler = self.target.data
1597 except AttributeError:
1598 return
1599 try:
1600 data_handler(self.entity[text[1:-1]])
Armin Rigo9ed73062005-12-14 18:10:45 +00001601 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001602 from xml.parsers import expat
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001603 err = expat.error(
Armin Rigo9ed73062005-12-14 18:10:45 +00001604 "undefined entity %s: line %d, column %d" %
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001605 (text, self.parser.ErrorLineNumber,
1606 self.parser.ErrorColumnNumber)
Armin Rigo9ed73062005-12-14 18:10:45 +00001607 )
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001608 err.code = 11 # XML_ERROR_UNDEFINED_ENTITY
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001609 err.lineno = self.parser.ErrorLineNumber
1610 err.offset = self.parser.ErrorColumnNumber
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001611 raise err
Armin Rigo9ed73062005-12-14 18:10:45 +00001612 elif prefix == "<" and text[:9] == "<!DOCTYPE":
1613 self._doctype = [] # inside a doctype declaration
1614 elif self._doctype is not None:
1615 # parse doctype contents
1616 if prefix == ">":
1617 self._doctype = None
1618 return
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001619 text = text.strip()
Armin Rigo9ed73062005-12-14 18:10:45 +00001620 if not text:
1621 return
1622 self._doctype.append(text)
1623 n = len(self._doctype)
1624 if n > 2:
1625 type = self._doctype[1]
1626 if type == "PUBLIC" and n == 4:
1627 name, type, pubid, system = self._doctype
1628 elif type == "SYSTEM" and n == 3:
1629 name, type, system = self._doctype
1630 pubid = None
1631 else:
1632 return
1633 if pubid:
1634 pubid = pubid[1:-1]
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001635 if hasattr(self.target, "doctype"):
1636 self.target.doctype(name, pubid, system[1:-1])
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001637 elif self.doctype != self._XMLParser__doctype:
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001638 # warn about deprecated call
1639 self._XMLParser__doctype(name, pubid, system[1:-1])
1640 self.doctype(name, pubid, system[1:-1])
Armin Rigo9ed73062005-12-14 18:10:45 +00001641 self._doctype = None
1642
1643 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001644 # (Deprecated) Handles a doctype declaration.
Armin Rigo9ed73062005-12-14 18:10:45 +00001645 #
1646 # @param name Doctype name.
1647 # @param pubid Public identifier.
1648 # @param system System identifier.
1649
1650 def doctype(self, name, pubid, system):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001651 """This method of XMLParser is deprecated."""
1652 warnings.warn(
1653 "This method of XMLParser is deprecated. Define doctype() "
1654 "method on the TreeBuilder target.",
1655 DeprecationWarning,
1656 )
1657
1658 # sentinel, if doctype is redefined in a subclass
1659 __doctype = doctype
Armin Rigo9ed73062005-12-14 18:10:45 +00001660
1661 ##
1662 # Feeds data to the parser.
1663 #
1664 # @param data Encoded data.
1665
1666 def feed(self, data):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001667 try:
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001668 self.parser.Parse(data, 0)
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001669 except self._error as v:
1670 self._raiseerror(v)
Armin Rigo9ed73062005-12-14 18:10:45 +00001671
1672 ##
1673 # Finishes feeding data to the parser.
1674 #
1675 # @return An element structure.
1676 # @defreturn Element
1677
1678 def close(self):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001679 try:
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001680 self.parser.Parse("", 1) # end of data
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001681 except self._error as v:
1682 self._raiseerror(v)
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001683 try:
Florent Xiclunafb067462012-03-05 11:42:49 +01001684 close_handler = self.target.close
1685 except AttributeError:
1686 pass
1687 else:
1688 return close_handler()
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001689 finally:
1690 # get rid of circular references
1691 del self.parser, self._parser
1692 del self.target, self._target
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001693
Florent Xiclunaa72a98f2012-02-13 11:03:30 +01001694
1695# Import the C accelerators
1696try:
1697 # Element, SubElement, ParseError, TreeBuilder, XMLParser
1698 from _elementtree import *
1699except ImportError:
1700 pass
1701else:
1702 # Overwrite 'ElementTree.parse' and 'iterparse' to use the C XMLParser
1703
1704 class ElementTree(ElementTree):
1705 def parse(self, source, parser=None):
1706 close_source = False
1707 if not hasattr(source, 'read'):
1708 source = open(source, 'rb')
1709 close_source = True
1710 try:
1711 if parser is not None:
1712 while True:
1713 data = source.read(65536)
1714 if not data:
1715 break
1716 parser.feed(data)
1717 self._root = parser.close()
1718 else:
1719 parser = XMLParser()
1720 self._root = parser._parse(source)
1721 return self._root
1722 finally:
1723 if close_source:
1724 source.close()
1725
1726 class iterparse:
1727 root = None
1728 def __init__(self, file, events=None):
1729 self._close_file = False
1730 if not hasattr(file, 'read'):
1731 file = open(file, 'rb')
1732 self._close_file = True
1733 self._file = file
1734 self._events = []
1735 self._index = 0
1736 self._error = None
1737 self.root = self._root = None
1738 b = TreeBuilder()
1739 self._parser = XMLParser(b)
1740 self._parser._setevents(self._events, events)
1741
1742 def __next__(self):
1743 while True:
1744 try:
1745 item = self._events[self._index]
1746 self._index += 1
1747 return item
1748 except IndexError:
1749 pass
1750 if self._error:
1751 e = self._error
1752 self._error = None
1753 raise e
1754 if self._parser is None:
1755 self.root = self._root
1756 if self._close_file:
1757 self._file.close()
1758 raise StopIteration
1759 # load event buffer
1760 del self._events[:]
1761 self._index = 0
1762 data = self._file.read(16384)
1763 if data:
1764 try:
1765 self._parser.feed(data)
1766 except SyntaxError as exc:
1767 self._error = exc
1768 else:
1769 self._root = self._parser.close()
1770 self._parser = None
1771
1772 def __iter__(self):
1773 return self
1774
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001775# compatibility
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001776XMLTreeBuilder = XMLParser
1777
1778# workaround circular import.
1779try:
1780 from ElementC14N import _serialize_c14n
1781 _serialize["c14n"] = _serialize_c14n
1782except ImportError:
1783 pass