blob: 5f974f65b08121b60dcf833567364e0f29116008 [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):
208 attrib = attrib.copy()
209 attrib.update(extra)
Armin Rigo9ed73062005-12-14 18:10:45 +0000210 self.tag = tag
211 self.attrib = attrib
212 self._children = []
213
214 def __repr__(self):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000215 return "<Element %s at 0x%x>" % (repr(self.tag), id(self))
Armin Rigo9ed73062005-12-14 18:10:45 +0000216
217 ##
218 # Creates a new element object of the same type as this element.
219 #
220 # @param tag Element tag.
221 # @param attrib Element attributes, given as a dictionary.
222 # @return A new element instance.
223
224 def makeelement(self, tag, attrib):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000225 return self.__class__(tag, attrib)
Armin Rigo9ed73062005-12-14 18:10:45 +0000226
227 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000228 # (Experimental) Copies the current element. This creates a
229 # shallow copy; subelements will be shared with the original tree.
230 #
231 # @return A new element instance.
232
233 def copy(self):
234 elem = self.makeelement(self.tag, self.attrib)
235 elem.text = self.text
236 elem.tail = self.tail
237 elem[:] = self
238 return elem
239
240 ##
241 # Returns the number of subelements. Note that this only counts
242 # full elements; to check if there's any content in an element, you
243 # have to check both the length and the <b>text</b> attribute.
Armin Rigo9ed73062005-12-14 18:10:45 +0000244 #
245 # @return The number of subelements.
246
247 def __len__(self):
248 return len(self._children)
249
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000250 def __bool__(self):
251 warnings.warn(
252 "The behavior of this method will change in future versions. "
253 "Use specific 'len(elem)' or 'elem is not None' test instead.",
254 FutureWarning, stacklevel=2
255 )
256 return len(self._children) != 0 # emulate old behaviour, for now
257
Armin Rigo9ed73062005-12-14 18:10:45 +0000258 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000259 # Returns the given subelement, by index.
Armin Rigo9ed73062005-12-14 18:10:45 +0000260 #
261 # @param index What subelement to return.
262 # @return The given subelement.
263 # @exception IndexError If the given element does not exist.
264
265 def __getitem__(self, index):
266 return self._children[index]
267
268 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000269 # Replaces the given subelement, by index.
Armin Rigo9ed73062005-12-14 18:10:45 +0000270 #
271 # @param index What subelement to replace.
272 # @param element The new element value.
273 # @exception IndexError If the given element does not exist.
Armin Rigo9ed73062005-12-14 18:10:45 +0000274
275 def __setitem__(self, index, element):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000276 # if isinstance(index, slice):
277 # for elt in element:
278 # assert iselement(elt)
279 # else:
280 # assert iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000281 self._children[index] = element
282
283 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000284 # Deletes the given subelement, by index.
Armin Rigo9ed73062005-12-14 18:10:45 +0000285 #
286 # @param index What subelement to delete.
287 # @exception IndexError If the given element does not exist.
288
289 def __delitem__(self, index):
290 del self._children[index]
291
292 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000293 # Adds a subelement to the end of this element. In document order,
294 # the new element will appear after the last existing subelement (or
295 # directly after the text, if it's the first subelement), but before
296 # the end tag for this element.
Armin Rigo9ed73062005-12-14 18:10:45 +0000297 #
298 # @param element The element to add.
Armin Rigo9ed73062005-12-14 18:10:45 +0000299
300 def append(self, element):
Eli Bendersky396e8fc2012-03-23 14:24:20 +0200301 self._assert_is_element(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000302 self._children.append(element)
303
304 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000305 # Appends subelements from a sequence.
306 #
307 # @param elements A sequence object with zero or more elements.
308 # @since 1.3
309
310 def extend(self, elements):
Eli Bendersky396e8fc2012-03-23 14:24:20 +0200311 for element in elements:
312 self._assert_is_element(element)
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000313 self._children.extend(elements)
314
315 ##
Armin Rigo9ed73062005-12-14 18:10:45 +0000316 # Inserts a subelement at the given position in this element.
317 #
318 # @param index Where to insert the new subelement.
Armin Rigo9ed73062005-12-14 18:10:45 +0000319
320 def insert(self, index, element):
Eli Bendersky396e8fc2012-03-23 14:24:20 +0200321 self._assert_is_element(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000322 self._children.insert(index, element)
323
Eli Bendersky396e8fc2012-03-23 14:24:20 +0200324 def _assert_is_element(self, e):
325 if not isinstance(e, Element):
326 raise TypeError('expected an Element, not %s' % type(e).__name__)
327
Armin Rigo9ed73062005-12-14 18:10:45 +0000328 ##
329 # Removes a matching subelement. Unlike the <b>find</b> methods,
330 # this method compares elements based on identity, not on tag
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000331 # value or contents. To remove subelements by other means, the
332 # easiest way is often to use a list comprehension to select what
333 # elements to keep, and use slice assignment to update the parent
334 # element.
Armin Rigo9ed73062005-12-14 18:10:45 +0000335 #
336 # @param element What element to remove.
337 # @exception ValueError If a matching element could not be found.
Armin Rigo9ed73062005-12-14 18:10:45 +0000338
339 def remove(self, element):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000340 # assert iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000341 self._children.remove(element)
342
343 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000344 # (Deprecated) Returns all subelements. The elements are returned
345 # in document order.
Armin Rigo9ed73062005-12-14 18:10:45 +0000346 #
347 # @return A list of subelements.
348 # @defreturn list of Element instances
349
350 def getchildren(self):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000351 warnings.warn(
352 "This method will be removed in future versions. "
353 "Use 'list(elem)' or iteration over elem instead.",
354 DeprecationWarning, stacklevel=2
355 )
Armin Rigo9ed73062005-12-14 18:10:45 +0000356 return self._children
357
358 ##
359 # Finds the first matching subelement, by tag name or path.
360 #
361 # @param path What element to look for.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000362 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000363 # @return The first matching element, or None if no element was found.
364 # @defreturn Element or None
365
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000366 def find(self, path, namespaces=None):
367 return ElementPath.find(self, path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000368
369 ##
370 # Finds text for the first matching subelement, by tag name or path.
371 #
372 # @param path What element to look for.
373 # @param default What to return if the element was not found.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000374 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000375 # @return The text content of the first matching element, or the
376 # default value no element was found. Note that if the element
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000377 # is found, but has no text content, this method returns an
Armin Rigo9ed73062005-12-14 18:10:45 +0000378 # empty string.
379 # @defreturn string
380
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000381 def findtext(self, path, default=None, namespaces=None):
382 return ElementPath.findtext(self, path, default, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000383
384 ##
385 # Finds all matching subelements, by tag name or path.
386 #
387 # @param path What element to look for.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000388 # @keyparam namespaces Optional namespace prefix map.
389 # @return A list or other sequence containing all matching elements,
Armin Rigo9ed73062005-12-14 18:10:45 +0000390 # in document order.
391 # @defreturn list of Element instances
392
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000393 def findall(self, path, namespaces=None):
394 return ElementPath.findall(self, path, namespaces)
395
396 ##
397 # Finds all matching subelements, by tag name or path.
398 #
399 # @param path What element to look for.
400 # @keyparam namespaces Optional namespace prefix map.
401 # @return An iterator or sequence containing all matching elements,
402 # in document order.
403 # @defreturn a generated sequence of Element instances
404
405 def iterfind(self, path, namespaces=None):
406 return ElementPath.iterfind(self, path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000407
408 ##
409 # Resets an element. This function removes all subelements, clears
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000410 # all attributes, and sets the <b>text</b> and <b>tail</b> attributes
411 # to None.
Armin Rigo9ed73062005-12-14 18:10:45 +0000412
413 def clear(self):
414 self.attrib.clear()
415 self._children = []
416 self.text = self.tail = None
417
418 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000419 # Gets an element attribute. Equivalent to <b>attrib.get</b>, but
420 # some implementations may handle this a bit more efficiently.
Armin Rigo9ed73062005-12-14 18:10:45 +0000421 #
422 # @param key What attribute to look for.
423 # @param default What to return if the attribute was not found.
424 # @return The attribute value, or the default value, if the
425 # attribute was not found.
426 # @defreturn string or None
427
428 def get(self, key, default=None):
429 return self.attrib.get(key, default)
430
431 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000432 # Sets an element attribute. Equivalent to <b>attrib[key] = value</b>,
433 # but some implementations may handle this a bit more efficiently.
Armin Rigo9ed73062005-12-14 18:10:45 +0000434 #
435 # @param key What attribute to set.
436 # @param value The attribute value.
437
438 def set(self, key, value):
439 self.attrib[key] = value
440
441 ##
442 # Gets a list of attribute names. The names are returned in an
443 # arbitrary order (just like for an ordinary Python dictionary).
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000444 # Equivalent to <b>attrib.keys()</b>.
Armin Rigo9ed73062005-12-14 18:10:45 +0000445 #
446 # @return A list of element attribute names.
447 # @defreturn list of strings
448
449 def keys(self):
450 return self.attrib.keys()
451
452 ##
453 # Gets element attributes, as a sequence. The attributes are
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000454 # returned in an arbitrary order. Equivalent to <b>attrib.items()</b>.
Armin Rigo9ed73062005-12-14 18:10:45 +0000455 #
456 # @return A list of (name, value) tuples for all attributes.
457 # @defreturn list of (string, string) tuples
458
459 def items(self):
460 return self.attrib.items()
461
462 ##
463 # Creates a tree iterator. The iterator loops over this element
464 # and all subelements, in document order, and returns all elements
465 # with a matching tag.
466 # <p>
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000467 # If the tree structure is modified during iteration, new or removed
468 # elements may or may not be included. To get a stable set, use the
469 # list() function on the iterator, and loop over the resulting list.
Armin Rigo9ed73062005-12-14 18:10:45 +0000470 #
471 # @param tag What tags to look for (default is to return all elements).
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000472 # @return An iterator containing all the matching elements.
473 # @defreturn iterator
Armin Rigo9ed73062005-12-14 18:10:45 +0000474
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000475 def iter(self, tag=None):
Armin Rigo9ed73062005-12-14 18:10:45 +0000476 if tag == "*":
477 tag = None
478 if tag is None or self.tag == tag:
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000479 yield self
480 for e in self._children:
481 for e in e.iter(tag):
482 yield e
483
484 # compatibility
485 def getiterator(self, tag=None):
486 # Change for a DeprecationWarning in 1.4
487 warnings.warn(
488 "This method will be removed in future versions. "
489 "Use 'elem.iter()' or 'list(elem.iter())' instead.",
490 PendingDeprecationWarning, stacklevel=2
491 )
492 return list(self.iter(tag))
493
494 ##
495 # Creates a text iterator. The iterator loops over this element
496 # and all subelements, in document order, and returns all inner
497 # text.
498 #
499 # @return An iterator containing all inner text.
500 # @defreturn iterator
501
502 def itertext(self):
503 tag = self.tag
504 if not isinstance(tag, str) and tag is not None:
505 return
506 if self.text:
507 yield self.text
508 for e in self:
509 for s in e.itertext():
510 yield s
511 if e.tail:
512 yield e.tail
Armin Rigo9ed73062005-12-14 18:10:45 +0000513
514# compatibility
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000515_Element = _ElementInterface = Element
Armin Rigo9ed73062005-12-14 18:10:45 +0000516
517##
518# Subelement factory. This function creates an element instance, and
519# appends it to an existing element.
520# <p>
521# The element name, attribute names, and attribute values can be
522# either 8-bit ASCII strings or Unicode strings.
523#
524# @param parent The parent element.
525# @param tag The subelement name.
526# @param attrib An optional dictionary, containing element attributes.
527# @param **extra Additional attributes, given as keyword arguments.
528# @return An element instance.
529# @defreturn Element
530
531def SubElement(parent, tag, attrib={}, **extra):
532 attrib = attrib.copy()
533 attrib.update(extra)
534 element = parent.makeelement(tag, attrib)
535 parent.append(element)
536 return element
537
538##
539# Comment element factory. This factory function creates a special
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000540# element that will be serialized as an XML comment by the standard
541# serializer.
Armin Rigo9ed73062005-12-14 18:10:45 +0000542# <p>
543# The comment string can be either an 8-bit ASCII string or a Unicode
544# string.
545#
546# @param text A string containing the comment string.
547# @return An element instance, representing a comment.
548# @defreturn Element
549
550def Comment(text=None):
551 element = Element(Comment)
552 element.text = text
553 return element
554
555##
556# PI element factory. This factory function creates a special element
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000557# that will be serialized as an XML processing instruction by the standard
558# serializer.
Armin Rigo9ed73062005-12-14 18:10:45 +0000559#
560# @param target A string containing the PI target.
561# @param text A string containing the PI contents, if any.
562# @return An element instance, representing a PI.
563# @defreturn Element
564
565def ProcessingInstruction(target, text=None):
566 element = Element(ProcessingInstruction)
567 element.text = target
568 if text:
569 element.text = element.text + " " + text
570 return element
571
572PI = ProcessingInstruction
573
574##
575# QName wrapper. This can be used to wrap a QName attribute value, in
576# order to get proper namespace handling on output.
577#
578# @param text A string containing the QName value, in the form {uri}local,
579# or, if the tag argument is given, the URI part of a QName.
580# @param tag Optional tag. If given, the first argument is interpreted as
581# an URI, and this argument is interpreted as a local name.
582# @return An opaque object, representing the QName.
583
584class QName:
585 def __init__(self, text_or_uri, tag=None):
586 if tag:
587 text_or_uri = "{%s}%s" % (text_or_uri, tag)
588 self.text = text_or_uri
589 def __str__(self):
590 return self.text
Georg Brandlb56c0e22010-12-09 18:10:27 +0000591 def __repr__(self):
Georg Brandlc95c9182010-12-09 18:26:02 +0000592 return '<QName %r>' % (self.text,)
Armin Rigo9ed73062005-12-14 18:10:45 +0000593 def __hash__(self):
594 return hash(self.text)
Mark Dickinsona56c4672009-01-27 18:17:45 +0000595 def __le__(self, other):
Armin Rigo9ed73062005-12-14 18:10:45 +0000596 if isinstance(other, QName):
Mark Dickinsona56c4672009-01-27 18:17:45 +0000597 return self.text <= other.text
598 return self.text <= other
599 def __lt__(self, other):
600 if isinstance(other, QName):
601 return self.text < other.text
602 return self.text < other
603 def __ge__(self, other):
604 if isinstance(other, QName):
605 return self.text >= other.text
606 return self.text >= other
607 def __gt__(self, other):
608 if isinstance(other, QName):
609 return self.text > other.text
610 return self.text > other
611 def __eq__(self, other):
612 if isinstance(other, QName):
613 return self.text == other.text
614 return self.text == other
615 def __ne__(self, other):
616 if isinstance(other, QName):
617 return self.text != other.text
618 return self.text != other
Armin Rigo9ed73062005-12-14 18:10:45 +0000619
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000620# --------------------------------------------------------------------
621
Armin Rigo9ed73062005-12-14 18:10:45 +0000622##
623# ElementTree wrapper class. This class represents an entire element
624# hierarchy, and adds some extra support for serialization to and from
625# standard XML.
626#
627# @param element Optional root element.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000628# @keyparam file Optional file handle or file name. If given, the
Armin Rigo9ed73062005-12-14 18:10:45 +0000629# tree is initialized with the contents of this XML file.
630
631class ElementTree:
632
633 def __init__(self, element=None, file=None):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000634 # assert element is None or iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000635 self._root = element # first node
636 if file:
637 self.parse(file)
638
639 ##
640 # Gets the root element for this tree.
641 #
642 # @return An element instance.
643 # @defreturn Element
644
645 def getroot(self):
646 return self._root
647
648 ##
649 # Replaces the root element for this tree. This discards the
650 # current contents of the tree, and replaces it with the given
651 # element. Use with care.
652 #
653 # @param element An element instance.
654
655 def _setroot(self, element):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000656 # assert iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000657 self._root = element
658
659 ##
660 # Loads an external XML document into this element tree.
661 #
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000662 # @param source A file name or file object. If a file object is
663 # given, it only has to implement a <b>read(n)</b> method.
664 # @keyparam parser An optional parser instance. If not given, the
665 # standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +0000666 # @return The document root element.
667 # @defreturn Element
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000668 # @exception ParseError If the parser fails to parse the document.
Armin Rigo9ed73062005-12-14 18:10:45 +0000669
670 def parse(self, source, parser=None):
Antoine Pitroue033e062010-10-29 10:38:18 +0000671 close_source = False
Armin Rigo9ed73062005-12-14 18:10:45 +0000672 if not hasattr(source, "read"):
673 source = open(source, "rb")
Antoine Pitroue033e062010-10-29 10:38:18 +0000674 close_source = True
675 try:
676 if not parser:
677 parser = XMLParser(target=TreeBuilder())
678 while 1:
679 data = source.read(65536)
680 if not data:
681 break
682 parser.feed(data)
683 self._root = parser.close()
684 return self._root
685 finally:
686 if close_source:
687 source.close()
Armin Rigo9ed73062005-12-14 18:10:45 +0000688
689 ##
690 # Creates a tree iterator for the root element. The iterator loops
691 # over all elements in this tree, in document order.
692 #
693 # @param tag What tags to look for (default is to return all elements)
694 # @return An iterator.
695 # @defreturn iterator
696
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000697 def iter(self, tag=None):
698 # assert self._root is not None
699 return self._root.iter(tag)
700
701 # compatibility
Armin Rigo9ed73062005-12-14 18:10:45 +0000702 def getiterator(self, tag=None):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000703 # Change for a DeprecationWarning in 1.4
704 warnings.warn(
705 "This method will be removed in future versions. "
706 "Use 'tree.iter()' or 'list(tree.iter())' instead.",
707 PendingDeprecationWarning, stacklevel=2
708 )
709 return list(self.iter(tag))
Armin Rigo9ed73062005-12-14 18:10:45 +0000710
711 ##
712 # Finds the first toplevel element with given tag.
713 # Same as getroot().find(path).
714 #
715 # @param path What element to look for.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000716 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000717 # @return The first matching element, or None if no element was found.
718 # @defreturn Element or None
719
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000720 def find(self, path, namespaces=None):
721 # assert self._root is not None
Armin Rigo9ed73062005-12-14 18:10:45 +0000722 if path[:1] == "/":
723 path = "." + path
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000724 warnings.warn(
725 "This search is broken in 1.3 and earlier, and will be "
726 "fixed in a future version. If you rely on the current "
727 "behaviour, change it to %r" % path,
728 FutureWarning, stacklevel=2
729 )
730 return self._root.find(path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000731
732 ##
733 # Finds the element text for the first toplevel element with given
734 # tag. Same as getroot().findtext(path).
735 #
736 # @param path What toplevel element to look for.
737 # @param default What to return if the element was not found.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000738 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000739 # @return The text content of the first matching element, or the
740 # default value no element was found. Note that if the element
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000741 # is found, but has no text content, this method returns an
Armin Rigo9ed73062005-12-14 18:10:45 +0000742 # empty string.
743 # @defreturn string
744
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000745 def findtext(self, path, default=None, namespaces=None):
746 # assert self._root is not None
Armin Rigo9ed73062005-12-14 18:10:45 +0000747 if path[:1] == "/":
748 path = "." + path
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000749 warnings.warn(
750 "This search is broken in 1.3 and earlier, and will be "
751 "fixed in a future version. If you rely on the current "
752 "behaviour, change it to %r" % path,
753 FutureWarning, stacklevel=2
754 )
755 return self._root.findtext(path, default, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000756
757 ##
758 # Finds all toplevel elements with the given tag.
759 # Same as getroot().findall(path).
760 #
761 # @param path What element to look for.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000762 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000763 # @return A list or iterator containing all matching elements,
764 # in document order.
765 # @defreturn list of Element instances
766
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000767 def findall(self, path, namespaces=None):
768 # assert self._root is not None
Armin Rigo9ed73062005-12-14 18:10:45 +0000769 if path[:1] == "/":
770 path = "." + path
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000771 warnings.warn(
772 "This search is broken in 1.3 and earlier, and will be "
773 "fixed in a future version. If you rely on the current "
774 "behaviour, change it to %r" % path,
775 FutureWarning, stacklevel=2
776 )
777 return self._root.findall(path, namespaces)
778
779 ##
780 # Finds all matching subelements, by tag name or path.
781 # Same as getroot().iterfind(path).
782 #
783 # @param path What element to look for.
784 # @keyparam namespaces Optional namespace prefix map.
785 # @return An iterator or sequence containing all matching elements,
786 # in document order.
787 # @defreturn a generated sequence of Element instances
788
789 def iterfind(self, path, namespaces=None):
790 # assert self._root is not None
791 if path[:1] == "/":
792 path = "." + path
793 warnings.warn(
794 "This search is broken in 1.3 and earlier, and will be "
795 "fixed in a future version. If you rely on the current "
796 "behaviour, change it to %r" % path,
797 FutureWarning, stacklevel=2
798 )
799 return self._root.iterfind(path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000800
801 ##
802 # Writes the element tree to a file, as XML.
803 #
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000804 # @def write(file, **options)
Armin Rigo9ed73062005-12-14 18:10:45 +0000805 # @param file A file name, or a file object opened for writing.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000806 # @param **options Options, given as keyword arguments.
Florent Xiclunac17f1722010-08-08 19:48:29 +0000807 # @keyparam encoding Optional output encoding (default is US-ASCII).
808 # Use "unicode" to return a Unicode string.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000809 # @keyparam method Optional output method ("xml", "html", "text" or
810 # "c14n"; default is "xml").
811 # @keyparam xml_declaration Controls if an XML declaration should
812 # be added to the file. Use False for never, True for always,
Florent Xiclunac17f1722010-08-08 19:48:29 +0000813 # None for only if not US-ASCII or UTF-8 or Unicode. None is default.
Armin Rigo9ed73062005-12-14 18:10:45 +0000814
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000815 def write(self, file_or_filename,
816 # keyword arguments
817 encoding=None,
818 xml_declaration=None,
819 default_namespace=None,
820 method=None):
821 # assert self._root is not None
822 if not method:
823 method = "xml"
824 elif method not in _serialize:
825 # FIXME: raise an ImportError for c14n if ElementC14N is missing?
826 raise ValueError("unknown method %r" % method)
Florent Xiclunac17f1722010-08-08 19:48:29 +0000827 if not encoding:
828 if method == "c14n":
829 encoding = "utf-8"
830 else:
831 encoding = "us-ascii"
832 elif encoding == str: # lxml.etree compatibility.
833 encoding = "unicode"
834 else:
835 encoding = encoding.lower()
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000836 if hasattr(file_or_filename, "write"):
837 file = file_or_filename
Armin Rigo9ed73062005-12-14 18:10:45 +0000838 else:
Florent Xiclunac17f1722010-08-08 19:48:29 +0000839 if encoding != "unicode":
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000840 file = open(file_or_filename, "wb")
Armin Rigo9ed73062005-12-14 18:10:45 +0000841 else:
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000842 file = open(file_or_filename, "w")
Florent Xiclunac17f1722010-08-08 19:48:29 +0000843 if encoding != "unicode":
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000844 def write(text):
845 try:
846 return file.write(text.encode(encoding,
847 "xmlcharrefreplace"))
848 except (TypeError, AttributeError):
849 _raise_serialization_error(text)
850 else:
851 write = file.write
Florent Xiclunac17f1722010-08-08 19:48:29 +0000852 if method == "xml" and (xml_declaration or
853 (xml_declaration is None and
854 encoding not in ("utf-8", "us-ascii", "unicode"))):
855 declared_encoding = encoding
856 if encoding == "unicode":
857 # Retrieve the default encoding for the xml declaration
858 import locale
859 declared_encoding = locale.getpreferredencoding()
860 write("<?xml version='1.0' encoding='%s'?>\n" % declared_encoding)
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000861 if method == "text":
862 _serialize_text(write, self._root)
863 else:
864 qnames, namespaces = _namespaces(self._root, default_namespace)
865 serialize = _serialize[method]
866 serialize(write, self._root, qnames, namespaces)
867 if file_or_filename is not file:
868 file.close()
869
870 def write_c14n(self, file):
871 # lxml.etree compatibility. use output method instead
872 return self.write(file, method="c14n")
Armin Rigo9ed73062005-12-14 18:10:45 +0000873
874# --------------------------------------------------------------------
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000875# serialization support
876
877def _namespaces(elem, default_namespace=None):
878 # identify namespaces used in this tree
879
880 # maps qnames to *encoded* prefix:local names
881 qnames = {None: None}
882
883 # maps uri:s to prefixes
884 namespaces = {}
885 if default_namespace:
886 namespaces[default_namespace] = ""
887
888 def add_qname(qname):
889 # calculate serialized qname representation
890 try:
891 if qname[:1] == "{":
892 uri, tag = qname[1:].rsplit("}", 1)
893 prefix = namespaces.get(uri)
894 if prefix is None:
895 prefix = _namespace_map.get(uri)
896 if prefix is None:
897 prefix = "ns%d" % len(namespaces)
898 if prefix != "xml":
899 namespaces[uri] = prefix
900 if prefix:
901 qnames[qname] = "%s:%s" % (prefix, tag)
902 else:
903 qnames[qname] = tag # default element
904 else:
905 if default_namespace:
906 # FIXME: can this be handled in XML 1.0?
907 raise ValueError(
908 "cannot use non-qualified names with "
909 "default_namespace option"
910 )
911 qnames[qname] = qname
912 except TypeError:
913 _raise_serialization_error(qname)
914
915 # populate qname and namespaces table
916 try:
917 iterate = elem.iter
918 except AttributeError:
919 iterate = elem.getiterator # cET compatibility
920 for elem in iterate():
921 tag = elem.tag
Senthil Kumaranec30b3d2010-11-09 02:36:59 +0000922 if isinstance(tag, QName):
923 if tag.text not in qnames:
924 add_qname(tag.text)
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000925 elif isinstance(tag, str):
926 if tag not in qnames:
927 add_qname(tag)
928 elif tag is not None and tag is not Comment and tag is not PI:
929 _raise_serialization_error(tag)
930 for key, value in elem.items():
931 if isinstance(key, QName):
932 key = key.text
933 if key not in qnames:
934 add_qname(key)
935 if isinstance(value, QName) and value.text not in qnames:
936 add_qname(value.text)
937 text = elem.text
938 if isinstance(text, QName) and text.text not in qnames:
939 add_qname(text.text)
940 return qnames, namespaces
941
942def _serialize_xml(write, elem, qnames, namespaces):
943 tag = elem.tag
944 text = elem.text
945 if tag is Comment:
946 write("<!--%s-->" % text)
947 elif tag is ProcessingInstruction:
948 write("<?%s?>" % text)
949 else:
950 tag = qnames[tag]
951 if tag is None:
952 if text:
953 write(_escape_cdata(text))
954 for e in elem:
955 _serialize_xml(write, e, qnames, None)
956 else:
957 write("<" + tag)
958 items = list(elem.items())
959 if items or namespaces:
960 if namespaces:
961 for v, k in sorted(namespaces.items(),
962 key=lambda x: x[1]): # sort on prefix
963 if k:
964 k = ":" + k
965 write(" xmlns%s=\"%s\"" % (
966 k,
967 _escape_attrib(v)
968 ))
969 for k, v in sorted(items): # lexical order
970 if isinstance(k, QName):
971 k = k.text
972 if isinstance(v, QName):
973 v = qnames[v.text]
974 else:
975 v = _escape_attrib(v)
976 write(" %s=\"%s\"" % (qnames[k], v))
977 if text or len(elem):
978 write(">")
979 if text:
980 write(_escape_cdata(text))
981 for e in elem:
982 _serialize_xml(write, e, qnames, None)
983 write("</" + tag + ">")
984 else:
985 write(" />")
986 if elem.tail:
987 write(_escape_cdata(elem.tail))
988
989HTML_EMPTY = ("area", "base", "basefont", "br", "col", "frame", "hr",
990 "img", "input", "isindex", "link", "meta" "param")
991
992try:
993 HTML_EMPTY = set(HTML_EMPTY)
994except NameError:
995 pass
996
997def _serialize_html(write, elem, qnames, namespaces):
998 tag = elem.tag
999 text = elem.text
1000 if tag is Comment:
1001 write("<!--%s-->" % _escape_cdata(text))
1002 elif tag is ProcessingInstruction:
1003 write("<?%s?>" % _escape_cdata(text))
1004 else:
1005 tag = qnames[tag]
1006 if tag is None:
1007 if text:
1008 write(_escape_cdata(text))
1009 for e in elem:
1010 _serialize_html(write, e, qnames, None)
1011 else:
1012 write("<" + tag)
1013 items = list(elem.items())
1014 if items or namespaces:
1015 if namespaces:
1016 for v, k in sorted(namespaces.items(),
1017 key=lambda x: x[1]): # sort on prefix
1018 if k:
1019 k = ":" + k
1020 write(" xmlns%s=\"%s\"" % (
1021 k,
1022 _escape_attrib(v)
1023 ))
1024 for k, v in sorted(items): # lexical order
1025 if isinstance(k, QName):
1026 k = k.text
1027 if isinstance(v, QName):
1028 v = qnames[v.text]
1029 else:
1030 v = _escape_attrib_html(v)
1031 # FIXME: handle boolean attributes
1032 write(" %s=\"%s\"" % (qnames[k], v))
1033 write(">")
1034 tag = tag.lower()
1035 if text:
1036 if tag == "script" or tag == "style":
1037 write(text)
1038 else:
1039 write(_escape_cdata(text))
1040 for e in elem:
1041 _serialize_html(write, e, qnames, None)
1042 if tag not in HTML_EMPTY:
1043 write("</" + tag + ">")
1044 if elem.tail:
1045 write(_escape_cdata(elem.tail))
1046
1047def _serialize_text(write, elem):
1048 for part in elem.itertext():
1049 write(part)
1050 if elem.tail:
1051 write(elem.tail)
1052
1053_serialize = {
1054 "xml": _serialize_xml,
1055 "html": _serialize_html,
1056 "text": _serialize_text,
1057# this optional method is imported at the end of the module
1058# "c14n": _serialize_c14n,
1059}
Armin Rigo9ed73062005-12-14 18:10:45 +00001060
1061##
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001062# Registers a namespace prefix. The registry is global, and any
1063# existing mapping for either the given prefix or the namespace URI
1064# will be removed.
Armin Rigo9ed73062005-12-14 18:10:45 +00001065#
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001066# @param prefix Namespace prefix.
1067# @param uri Namespace uri. Tags and attributes in this namespace
1068# will be serialized with the given prefix, if at all possible.
1069# @exception ValueError If the prefix is reserved, or is otherwise
1070# invalid.
Armin Rigo9ed73062005-12-14 18:10:45 +00001071
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001072def register_namespace(prefix, uri):
1073 if re.match("ns\d+$", prefix):
1074 raise ValueError("Prefix format reserved for internal use")
Georg Brandl90b20672010-12-28 10:38:33 +00001075 for k, v in list(_namespace_map.items()):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001076 if k == uri or v == prefix:
1077 del _namespace_map[k]
1078 _namespace_map[uri] = prefix
1079
1080_namespace_map = {
1081 # "well-known" namespace prefixes
1082 "http://www.w3.org/XML/1998/namespace": "xml",
1083 "http://www.w3.org/1999/xhtml": "html",
1084 "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
1085 "http://schemas.xmlsoap.org/wsdl/": "wsdl",
1086 # xml schema
1087 "http://www.w3.org/2001/XMLSchema": "xs",
1088 "http://www.w3.org/2001/XMLSchema-instance": "xsi",
1089 # dublin core
1090 "http://purl.org/dc/elements/1.1/": "dc",
1091}
Florent Xicluna16395052012-02-16 23:28:35 +01001092# For tests and troubleshooting
1093register_namespace._namespace_map = _namespace_map
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001094
1095def _raise_serialization_error(text):
1096 raise TypeError(
1097 "cannot serialize %r (type %s)" % (text, type(text).__name__)
1098 )
1099
1100def _escape_cdata(text):
1101 # escape character data
1102 try:
1103 # it's worth avoiding do-nothing calls for strings that are
1104 # shorter than 500 character, or so. assume that's, by far,
1105 # the most common case in most applications.
1106 if "&" in text:
1107 text = text.replace("&", "&amp;")
1108 if "<" in text:
1109 text = text.replace("<", "&lt;")
1110 if ">" in text:
1111 text = text.replace(">", "&gt;")
1112 return text
1113 except (TypeError, AttributeError):
1114 _raise_serialization_error(text)
1115
1116def _escape_attrib(text):
1117 # escape attribute value
1118 try:
1119 if "&" in text:
1120 text = text.replace("&", "&amp;")
1121 if "<" in text:
1122 text = text.replace("<", "&lt;")
1123 if ">" in text:
1124 text = text.replace(">", "&gt;")
1125 if "\"" in text:
1126 text = text.replace("\"", "&quot;")
1127 if "\n" in text:
1128 text = text.replace("\n", "&#10;")
1129 return text
1130 except (TypeError, AttributeError):
1131 _raise_serialization_error(text)
1132
1133def _escape_attrib_html(text):
1134 # escape attribute value
1135 try:
1136 if "&" in text:
1137 text = text.replace("&", "&amp;")
1138 if ">" in text:
1139 text = text.replace(">", "&gt;")
1140 if "\"" in text:
1141 text = text.replace("\"", "&quot;")
1142 return text
1143 except (TypeError, AttributeError):
1144 _raise_serialization_error(text)
1145
1146# --------------------------------------------------------------------
1147
1148##
1149# Generates a string representation of an XML element, including all
Florent Xiclunac17f1722010-08-08 19:48:29 +00001150# subelements. If encoding is "unicode", the return type is a string;
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001151# otherwise it is a bytes array.
1152#
1153# @param element An Element instance.
Florent Xiclunac17f1722010-08-08 19:48:29 +00001154# @keyparam encoding Optional output encoding (default is US-ASCII).
1155# Use "unicode" to return a Unicode string.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001156# @keyparam method Optional output method ("xml", "html", "text" or
1157# "c14n"; default is "xml").
1158# @return An (optionally) encoded string containing the XML data.
1159# @defreturn string
1160
1161def tostring(element, encoding=None, method=None):
1162 class dummy:
1163 pass
1164 data = []
1165 file = dummy()
1166 file.write = data.append
1167 ElementTree(element).write(file, encoding, method=method)
Florent Xiclunac17f1722010-08-08 19:48:29 +00001168 if encoding in (str, "unicode"):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001169 return "".join(data)
Florent Xiclunac17f1722010-08-08 19:48:29 +00001170 else:
1171 return b"".join(data)
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001172
1173##
1174# Generates a string representation of an XML element, including all
Florent Xiclunac17f1722010-08-08 19:48:29 +00001175# subelements. If encoding is False, the string is returned as a
1176# sequence of string fragments; otherwise it is a sequence of
1177# bytestrings.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001178#
1179# @param element An Element instance.
1180# @keyparam encoding Optional output encoding (default is US-ASCII).
Florent Xiclunac17f1722010-08-08 19:48:29 +00001181# Use "unicode" to return a Unicode string.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001182# @keyparam method Optional output method ("xml", "html", "text" or
1183# "c14n"; default is "xml").
1184# @return A sequence object containing the XML data.
1185# @defreturn sequence
1186# @since 1.3
1187
1188def tostringlist(element, encoding=None, method=None):
1189 class dummy:
1190 pass
1191 data = []
1192 file = dummy()
1193 file.write = data.append
1194 ElementTree(element).write(file, encoding, method=method)
1195 # FIXME: merge small fragments into larger parts
1196 return data
Armin Rigo9ed73062005-12-14 18:10:45 +00001197
1198##
1199# Writes an element tree or element structure to sys.stdout. This
1200# function should be used for debugging only.
1201# <p>
1202# The exact output format is implementation dependent. In this
1203# version, it's written as an ordinary XML file.
1204#
1205# @param elem An element tree or an individual element.
1206
1207def dump(elem):
1208 # debugging
1209 if not isinstance(elem, ElementTree):
1210 elem = ElementTree(elem)
Florent Xiclunac17f1722010-08-08 19:48:29 +00001211 elem.write(sys.stdout, encoding="unicode")
Armin Rigo9ed73062005-12-14 18:10:45 +00001212 tail = elem.getroot().tail
1213 if not tail or tail[-1] != "\n":
1214 sys.stdout.write("\n")
1215
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001216# --------------------------------------------------------------------
1217# parsing
Armin Rigo9ed73062005-12-14 18:10:45 +00001218
1219##
1220# Parses an XML document into an element tree.
1221#
1222# @param source A filename or file object containing XML data.
1223# @param parser An optional parser instance. If not given, the
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001224# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001225# @return An ElementTree instance
1226
1227def parse(source, parser=None):
1228 tree = ElementTree()
1229 tree.parse(source, parser)
1230 return tree
1231
1232##
1233# Parses an XML document into an element tree incrementally, and reports
1234# what's going on to the user.
1235#
1236# @param source A filename or file object containing XML data.
1237# @param events A list of events to report back. If omitted, only "end"
1238# events are reported.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001239# @param parser An optional parser instance. If not given, the
1240# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001241# @return A (event, elem) iterator.
1242
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001243def iterparse(source, events=None, parser=None):
Antoine Pitroue033e062010-10-29 10:38:18 +00001244 close_source = False
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001245 if not hasattr(source, "read"):
1246 source = open(source, "rb")
Antoine Pitroue033e062010-10-29 10:38:18 +00001247 close_source = True
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001248 if not parser:
1249 parser = XMLParser(target=TreeBuilder())
Antoine Pitroue033e062010-10-29 10:38:18 +00001250 return _IterParseIterator(source, events, parser, close_source)
Armin Rigo9ed73062005-12-14 18:10:45 +00001251
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001252class _IterParseIterator:
1253
Antoine Pitroue033e062010-10-29 10:38:18 +00001254 def __init__(self, source, events, parser, close_source=False):
Armin Rigo9ed73062005-12-14 18:10:45 +00001255 self._file = source
Antoine Pitroue033e062010-10-29 10:38:18 +00001256 self._close_file = close_source
Armin Rigo9ed73062005-12-14 18:10:45 +00001257 self._events = []
1258 self._index = 0
Florent Xicluna91d51932011-11-01 23:31:09 +01001259 self._error = None
Armin Rigo9ed73062005-12-14 18:10:45 +00001260 self.root = self._root = None
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001261 self._parser = parser
Armin Rigo9ed73062005-12-14 18:10:45 +00001262 # wire up the parser for event reporting
1263 parser = self._parser._parser
1264 append = self._events.append
1265 if events is None:
1266 events = ["end"]
1267 for event in events:
1268 if event == "start":
1269 try:
1270 parser.ordered_attributes = 1
1271 parser.specified_attributes = 1
1272 def handler(tag, attrib_in, event=event, append=append,
1273 start=self._parser._start_list):
1274 append((event, start(tag, attrib_in)))
1275 parser.StartElementHandler = handler
1276 except AttributeError:
1277 def handler(tag, attrib_in, event=event, append=append,
1278 start=self._parser._start):
1279 append((event, start(tag, attrib_in)))
1280 parser.StartElementHandler = handler
1281 elif event == "end":
1282 def handler(tag, event=event, append=append,
1283 end=self._parser._end):
1284 append((event, end(tag)))
1285 parser.EndElementHandler = handler
1286 elif event == "start-ns":
1287 def handler(prefix, uri, event=event, append=append):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001288 append((event, (prefix or "", uri or "")))
Armin Rigo9ed73062005-12-14 18:10:45 +00001289 parser.StartNamespaceDeclHandler = handler
1290 elif event == "end-ns":
1291 def handler(prefix, event=event, append=append):
1292 append((event, None))
1293 parser.EndNamespaceDeclHandler = handler
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001294 else:
1295 raise ValueError("unknown event %r" % event)
Armin Rigo9ed73062005-12-14 18:10:45 +00001296
Georg Brandla18af4e2007-04-21 15:47:16 +00001297 def __next__(self):
Armin Rigo9ed73062005-12-14 18:10:45 +00001298 while 1:
1299 try:
1300 item = self._events[self._index]
Florent Xicluna91d51932011-11-01 23:31:09 +01001301 self._index += 1
Armin Rigo9ed73062005-12-14 18:10:45 +00001302 return item
Florent Xicluna91d51932011-11-01 23:31:09 +01001303 except IndexError:
1304 pass
1305 if self._error:
1306 e = self._error
1307 self._error = None
1308 raise e
1309 if self._parser is None:
1310 self.root = self._root
1311 if self._close_file:
1312 self._file.close()
1313 raise StopIteration
1314 # load event buffer
1315 del self._events[:]
1316 self._index = 0
1317 data = self._file.read(16384)
1318 if data:
1319 try:
1320 self._parser.feed(data)
1321 except SyntaxError as exc:
1322 self._error = exc
1323 else:
1324 self._root = self._parser.close()
1325 self._parser = None
Armin Rigo9ed73062005-12-14 18:10:45 +00001326
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001327 def __iter__(self):
1328 return self
Armin Rigo9ed73062005-12-14 18:10:45 +00001329
1330##
1331# Parses an XML document from a string constant. This function can
1332# be used to embed "XML literals" in Python code.
1333#
1334# @param source A string containing XML data.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001335# @param parser An optional parser instance. If not given, the
1336# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001337# @return An Element instance.
1338# @defreturn Element
1339
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001340def XML(text, parser=None):
1341 if not parser:
1342 parser = XMLParser(target=TreeBuilder())
Armin Rigo9ed73062005-12-14 18:10:45 +00001343 parser.feed(text)
1344 return parser.close()
1345
1346##
1347# Parses an XML document from a string constant, and also returns
1348# a dictionary which maps from element id:s to elements.
1349#
1350# @param source A string containing XML data.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001351# @param parser An optional parser instance. If not given, the
1352# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001353# @return A tuple containing an Element instance and a dictionary.
1354# @defreturn (Element, dictionary)
1355
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001356def XMLID(text, parser=None):
1357 if not parser:
1358 parser = XMLParser(target=TreeBuilder())
Armin Rigo9ed73062005-12-14 18:10:45 +00001359 parser.feed(text)
1360 tree = parser.close()
1361 ids = {}
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001362 for elem in tree.iter():
Armin Rigo9ed73062005-12-14 18:10:45 +00001363 id = elem.get("id")
1364 if id:
1365 ids[id] = elem
1366 return tree, ids
1367
1368##
1369# Parses an XML document from a string constant. Same as {@link #XML}.
1370#
1371# @def fromstring(text)
1372# @param source A string containing XML data.
1373# @return An Element instance.
1374# @defreturn Element
1375
1376fromstring = XML
1377
1378##
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001379# Parses an XML document from a sequence of string fragments.
Armin Rigo9ed73062005-12-14 18:10:45 +00001380#
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001381# @param sequence A list or other sequence containing XML data fragments.
1382# @param parser An optional parser instance. If not given, the
1383# standard {@link XMLParser} parser is used.
1384# @return An Element instance.
1385# @defreturn Element
1386# @since 1.3
Armin Rigo9ed73062005-12-14 18:10:45 +00001387
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001388def fromstringlist(sequence, parser=None):
1389 if not parser:
1390 parser = XMLParser(target=TreeBuilder())
1391 for text in sequence:
1392 parser.feed(text)
1393 return parser.close()
1394
1395# --------------------------------------------------------------------
Armin Rigo9ed73062005-12-14 18:10:45 +00001396
1397##
1398# Generic element structure builder. This builder converts a sequence
1399# of {@link #TreeBuilder.start}, {@link #TreeBuilder.data}, and {@link
1400# #TreeBuilder.end} method calls to a well-formed element structure.
1401# <p>
1402# You can use this class to build an element structure using a custom XML
1403# parser, or a parser for some other XML-like format.
1404#
1405# @param element_factory Optional element factory. This factory
1406# is called to create new Element instances, as necessary.
1407
1408class TreeBuilder:
1409
1410 def __init__(self, element_factory=None):
1411 self._data = [] # data collector
1412 self._elem = [] # element stack
1413 self._last = None # last element
1414 self._tail = None # true if we're after an end tag
1415 if element_factory is None:
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001416 element_factory = Element
Armin Rigo9ed73062005-12-14 18:10:45 +00001417 self._factory = element_factory
1418
1419 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001420 # Flushes the builder buffers, and returns the toplevel document
Armin Rigo9ed73062005-12-14 18:10:45 +00001421 # element.
1422 #
1423 # @return An Element instance.
1424 # @defreturn Element
1425
1426 def close(self):
1427 assert len(self._elem) == 0, "missing end tags"
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001428 assert self._last is not None, "missing toplevel element"
Armin Rigo9ed73062005-12-14 18:10:45 +00001429 return self._last
1430
1431 def _flush(self):
1432 if self._data:
1433 if self._last is not None:
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001434 text = "".join(self._data)
Armin Rigo9ed73062005-12-14 18:10:45 +00001435 if self._tail:
1436 assert self._last.tail is None, "internal error (tail)"
1437 self._last.tail = text
1438 else:
1439 assert self._last.text is None, "internal error (text)"
1440 self._last.text = text
1441 self._data = []
1442
1443 ##
1444 # Adds text to the current element.
1445 #
1446 # @param data A string. This should be either an 8-bit string
1447 # containing ASCII text, or a Unicode string.
1448
1449 def data(self, data):
1450 self._data.append(data)
1451
1452 ##
1453 # Opens a new element.
1454 #
1455 # @param tag The element name.
1456 # @param attrib A dictionary containing element attributes.
1457 # @return The opened element.
1458 # @defreturn Element
1459
1460 def start(self, tag, attrs):
1461 self._flush()
1462 self._last = elem = self._factory(tag, attrs)
1463 if self._elem:
1464 self._elem[-1].append(elem)
1465 self._elem.append(elem)
1466 self._tail = 0
1467 return elem
1468
1469 ##
1470 # Closes the current element.
1471 #
1472 # @param tag The element name.
1473 # @return The closed element.
1474 # @defreturn Element
1475
1476 def end(self, tag):
1477 self._flush()
1478 self._last = self._elem.pop()
1479 assert self._last.tag == tag,\
1480 "end tag mismatch (expected %s, got %s)" % (
1481 self._last.tag, tag)
1482 self._tail = 1
1483 return self._last
1484
1485##
1486# Element structure builder for XML source data, based on the
1487# <b>expat</b> parser.
1488#
1489# @keyparam target Target object. If omitted, the builder uses an
1490# instance of the standard {@link #TreeBuilder} class.
1491# @keyparam html Predefine HTML entities. This flag is not supported
1492# by the current implementation.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001493# @keyparam encoding Optional encoding. If given, the value overrides
1494# the encoding specified in the XML file.
Armin Rigo9ed73062005-12-14 18:10:45 +00001495# @see #ElementTree
1496# @see #TreeBuilder
1497
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001498class XMLParser:
Armin Rigo9ed73062005-12-14 18:10:45 +00001499
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001500 def __init__(self, html=0, target=None, encoding=None):
Armin Rigo9ed73062005-12-14 18:10:45 +00001501 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001502 from xml.parsers import expat
Armin Rigo9ed73062005-12-14 18:10:45 +00001503 except ImportError:
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001504 try:
1505 import pyexpat as expat
1506 except ImportError:
1507 raise ImportError(
1508 "No module named expat; use SimpleXMLTreeBuilder instead"
1509 )
1510 parser = expat.ParserCreate(encoding, "}")
Armin Rigo9ed73062005-12-14 18:10:45 +00001511 if target is None:
1512 target = TreeBuilder()
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001513 # underscored names are provided for compatibility only
1514 self.parser = self._parser = parser
1515 self.target = self._target = target
1516 self._error = expat.error
Armin Rigo9ed73062005-12-14 18:10:45 +00001517 self._names = {} # name memo cache
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001518 # main callbacks
Armin Rigo9ed73062005-12-14 18:10:45 +00001519 parser.DefaultHandlerExpand = self._default
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001520 if hasattr(target, 'start'):
1521 parser.StartElementHandler = self._start
1522 if hasattr(target, 'end'):
1523 parser.EndElementHandler = self._end
1524 if hasattr(target, 'data'):
1525 parser.CharacterDataHandler = target.data
1526 # miscellaneous callbacks
1527 if hasattr(target, 'comment'):
1528 parser.CommentHandler = target.comment
1529 if hasattr(target, 'pi'):
1530 parser.ProcessingInstructionHandler = target.pi
Armin Rigo9ed73062005-12-14 18:10:45 +00001531 # let expat do the buffering, if supported
1532 try:
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001533 parser.buffer_text = 1
Armin Rigo9ed73062005-12-14 18:10:45 +00001534 except AttributeError:
1535 pass
1536 # use new-style attribute handling, if supported
1537 try:
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001538 parser.ordered_attributes = 1
1539 parser.specified_attributes = 1
1540 if hasattr(target, 'start'):
1541 parser.StartElementHandler = self._start_list
Armin Rigo9ed73062005-12-14 18:10:45 +00001542 except AttributeError:
1543 pass
Armin Rigo9ed73062005-12-14 18:10:45 +00001544 self._doctype = None
1545 self.entity = {}
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001546 try:
1547 self.version = "Expat %d.%d.%d" % expat.version_info
1548 except AttributeError:
1549 pass # unknown
1550
1551 def _raiseerror(self, value):
1552 err = ParseError(value)
1553 err.code = value.code
1554 err.position = value.lineno, value.offset
1555 raise err
Armin Rigo9ed73062005-12-14 18:10:45 +00001556
Armin Rigo9ed73062005-12-14 18:10:45 +00001557 def _fixname(self, key):
1558 # expand qname, and convert name string to ascii, if possible
1559 try:
1560 name = self._names[key]
1561 except KeyError:
1562 name = key
1563 if "}" in name:
1564 name = "{" + name
Martin v. Löwisf30bb0e2007-07-28 11:40:46 +00001565 self._names[key] = name
Armin Rigo9ed73062005-12-14 18:10:45 +00001566 return name
1567
1568 def _start(self, tag, attrib_in):
1569 fixname = self._fixname
1570 tag = fixname(tag)
1571 attrib = {}
1572 for key, value in attrib_in.items():
Martin v. Löwisf30bb0e2007-07-28 11:40:46 +00001573 attrib[fixname(key)] = value
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001574 return self.target.start(tag, attrib)
Armin Rigo9ed73062005-12-14 18:10:45 +00001575
1576 def _start_list(self, tag, attrib_in):
1577 fixname = self._fixname
1578 tag = fixname(tag)
1579 attrib = {}
1580 if attrib_in:
1581 for i in range(0, len(attrib_in), 2):
Martin v. Löwisf30bb0e2007-07-28 11:40:46 +00001582 attrib[fixname(attrib_in[i])] = attrib_in[i+1]
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001583 return self.target.start(tag, attrib)
Armin Rigo9ed73062005-12-14 18:10:45 +00001584
Armin Rigo9ed73062005-12-14 18:10:45 +00001585 def _end(self, tag):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001586 return self.target.end(self._fixname(tag))
1587
Armin Rigo9ed73062005-12-14 18:10:45 +00001588 def _default(self, text):
1589 prefix = text[:1]
1590 if prefix == "&":
1591 # deal with undefined entities
1592 try:
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001593 data_handler = self.target.data
1594 except AttributeError:
1595 return
1596 try:
1597 data_handler(self.entity[text[1:-1]])
Armin Rigo9ed73062005-12-14 18:10:45 +00001598 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001599 from xml.parsers import expat
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001600 err = expat.error(
Armin Rigo9ed73062005-12-14 18:10:45 +00001601 "undefined entity %s: line %d, column %d" %
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001602 (text, self.parser.ErrorLineNumber,
1603 self.parser.ErrorColumnNumber)
Armin Rigo9ed73062005-12-14 18:10:45 +00001604 )
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001605 err.code = 11 # XML_ERROR_UNDEFINED_ENTITY
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001606 err.lineno = self.parser.ErrorLineNumber
1607 err.offset = self.parser.ErrorColumnNumber
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001608 raise err
Armin Rigo9ed73062005-12-14 18:10:45 +00001609 elif prefix == "<" and text[:9] == "<!DOCTYPE":
1610 self._doctype = [] # inside a doctype declaration
1611 elif self._doctype is not None:
1612 # parse doctype contents
1613 if prefix == ">":
1614 self._doctype = None
1615 return
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001616 text = text.strip()
Armin Rigo9ed73062005-12-14 18:10:45 +00001617 if not text:
1618 return
1619 self._doctype.append(text)
1620 n = len(self._doctype)
1621 if n > 2:
1622 type = self._doctype[1]
1623 if type == "PUBLIC" and n == 4:
1624 name, type, pubid, system = self._doctype
1625 elif type == "SYSTEM" and n == 3:
1626 name, type, system = self._doctype
1627 pubid = None
1628 else:
1629 return
1630 if pubid:
1631 pubid = pubid[1:-1]
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001632 if hasattr(self.target, "doctype"):
1633 self.target.doctype(name, pubid, system[1:-1])
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001634 elif self.doctype != self._XMLParser__doctype:
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001635 # warn about deprecated call
1636 self._XMLParser__doctype(name, pubid, system[1:-1])
1637 self.doctype(name, pubid, system[1:-1])
Armin Rigo9ed73062005-12-14 18:10:45 +00001638 self._doctype = None
1639
1640 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001641 # (Deprecated) Handles a doctype declaration.
Armin Rigo9ed73062005-12-14 18:10:45 +00001642 #
1643 # @param name Doctype name.
1644 # @param pubid Public identifier.
1645 # @param system System identifier.
1646
1647 def doctype(self, name, pubid, system):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001648 """This method of XMLParser is deprecated."""
1649 warnings.warn(
1650 "This method of XMLParser is deprecated. Define doctype() "
1651 "method on the TreeBuilder target.",
1652 DeprecationWarning,
1653 )
1654
1655 # sentinel, if doctype is redefined in a subclass
1656 __doctype = doctype
Armin Rigo9ed73062005-12-14 18:10:45 +00001657
1658 ##
1659 # Feeds data to the parser.
1660 #
1661 # @param data Encoded data.
1662
1663 def feed(self, data):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001664 try:
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001665 self.parser.Parse(data, 0)
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001666 except self._error as v:
1667 self._raiseerror(v)
Armin Rigo9ed73062005-12-14 18:10:45 +00001668
1669 ##
1670 # Finishes feeding data to the parser.
1671 #
1672 # @return An element structure.
1673 # @defreturn Element
1674
1675 def close(self):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001676 try:
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001677 self.parser.Parse("", 1) # end of data
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001678 except self._error as v:
1679 self._raiseerror(v)
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001680 try:
Florent Xiclunafb067462012-03-05 11:42:49 +01001681 close_handler = self.target.close
1682 except AttributeError:
1683 pass
1684 else:
1685 return close_handler()
Florent Xicluna75b5e7e2012-03-05 10:42:19 +01001686 finally:
1687 # get rid of circular references
1688 del self.parser, self._parser
1689 del self.target, self._target
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001690
Florent Xiclunaa72a98f2012-02-13 11:03:30 +01001691
1692# Import the C accelerators
1693try:
1694 # Element, SubElement, ParseError, TreeBuilder, XMLParser
1695 from _elementtree import *
1696except ImportError:
1697 pass
1698else:
1699 # Overwrite 'ElementTree.parse' and 'iterparse' to use the C XMLParser
1700
1701 class ElementTree(ElementTree):
1702 def parse(self, source, parser=None):
1703 close_source = False
1704 if not hasattr(source, 'read'):
1705 source = open(source, 'rb')
1706 close_source = True
1707 try:
1708 if parser is not None:
1709 while True:
1710 data = source.read(65536)
1711 if not data:
1712 break
1713 parser.feed(data)
1714 self._root = parser.close()
1715 else:
1716 parser = XMLParser()
1717 self._root = parser._parse(source)
1718 return self._root
1719 finally:
1720 if close_source:
1721 source.close()
1722
1723 class iterparse:
1724 root = None
1725 def __init__(self, file, events=None):
1726 self._close_file = False
1727 if not hasattr(file, 'read'):
1728 file = open(file, 'rb')
1729 self._close_file = True
1730 self._file = file
1731 self._events = []
1732 self._index = 0
1733 self._error = None
1734 self.root = self._root = None
1735 b = TreeBuilder()
1736 self._parser = XMLParser(b)
1737 self._parser._setevents(self._events, events)
1738
1739 def __next__(self):
1740 while True:
1741 try:
1742 item = self._events[self._index]
1743 self._index += 1
1744 return item
1745 except IndexError:
1746 pass
1747 if self._error:
1748 e = self._error
1749 self._error = None
1750 raise e
1751 if self._parser is None:
1752 self.root = self._root
1753 if self._close_file:
1754 self._file.close()
1755 raise StopIteration
1756 # load event buffer
1757 del self._events[:]
1758 self._index = 0
1759 data = self._file.read(16384)
1760 if data:
1761 try:
1762 self._parser.feed(data)
1763 except SyntaxError as exc:
1764 self._error = exc
1765 else:
1766 self._root = self._parser.close()
1767 self._parser = None
1768
1769 def __iter__(self):
1770 return self
1771
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001772# compatibility
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001773XMLTreeBuilder = XMLParser
1774
1775# workaround circular import.
1776try:
1777 from ElementC14N import _serialize_c14n
1778 _serialize["c14n"] = _serialize_c14n
1779except ImportError:
1780 pass