blob: 9f5717e0091c8bef9ad54cc58d3c9660870750ec [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",
71 "XML",
Thomas Wouters0e3f5912006-08-11 14:57:12 +000072 "XMLParser", "XMLTreeBuilder",
Armin Rigo9ed73062005-12-14 18:10:45 +000073 ]
74
Florent Xiclunaf15351d2010-03-13 23:24:31 +000075VERSION = "1.3.0"
76
Armin Rigo9ed73062005-12-14 18:10:45 +000077##
78# The <b>Element</b> type is a flexible container object, designed to
79# store hierarchical data structures in memory. The type can be
80# described as a cross between a list and a dictionary.
81# <p>
82# Each element has a number of properties associated with it:
83# <ul>
84# <li>a <i>tag</i>. This is a string identifying what kind of data
85# this element represents (the element type, in other words).</li>
86# <li>a number of <i>attributes</i>, stored in a Python dictionary.</li>
87# <li>a <i>text</i> string.</li>
88# <li>an optional <i>tail</i> string.</li>
89# <li>a number of <i>child elements</i>, stored in a Python sequence</li>
90# </ul>
91#
Florent Xiclunaf15351d2010-03-13 23:24:31 +000092# To create an element instance, use the {@link #Element} constructor
93# or the {@link #SubElement} factory function.
Armin Rigo9ed73062005-12-14 18:10:45 +000094# <p>
95# The {@link #ElementTree} class can be used to wrap an element
96# structure, and convert it from and to XML.
97##
98
Florent Xiclunaf15351d2010-03-13 23:24:31 +000099import sys
100import re
101import warnings
Armin Rigo9ed73062005-12-14 18:10:45 +0000102
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):
151 # FIXME: not sure about this; might be a better idea to look
152 # for tag/attrib/text attributes
153 return isinstance(element, Element) or hasattr(element, "tag")
154
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):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000301 # assert iselement(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):
311 # for element in elements:
312 # assert iselement(element)
313 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):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000321 # assert iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000322 self._children.insert(index, element)
323
324 ##
325 # Removes a matching subelement. Unlike the <b>find</b> methods,
326 # this method compares elements based on identity, not on tag
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000327 # value or contents. To remove subelements by other means, the
328 # easiest way is often to use a list comprehension to select what
329 # elements to keep, and use slice assignment to update the parent
330 # element.
Armin Rigo9ed73062005-12-14 18:10:45 +0000331 #
332 # @param element What element to remove.
333 # @exception ValueError If a matching element could not be found.
Armin Rigo9ed73062005-12-14 18:10:45 +0000334
335 def remove(self, element):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000336 # assert iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000337 self._children.remove(element)
338
339 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000340 # (Deprecated) Returns all subelements. The elements are returned
341 # in document order.
Armin Rigo9ed73062005-12-14 18:10:45 +0000342 #
343 # @return A list of subelements.
344 # @defreturn list of Element instances
345
346 def getchildren(self):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000347 warnings.warn(
348 "This method will be removed in future versions. "
349 "Use 'list(elem)' or iteration over elem instead.",
350 DeprecationWarning, stacklevel=2
351 )
Armin Rigo9ed73062005-12-14 18:10:45 +0000352 return self._children
353
354 ##
355 # Finds the first matching subelement, by tag name or path.
356 #
357 # @param path What element to look for.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000358 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000359 # @return The first matching element, or None if no element was found.
360 # @defreturn Element or None
361
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000362 def find(self, path, namespaces=None):
363 return ElementPath.find(self, path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000364
365 ##
366 # Finds text for the first matching subelement, by tag name or path.
367 #
368 # @param path What element to look for.
369 # @param default What to return if the element was not found.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000370 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000371 # @return The text content of the first matching element, or the
372 # default value no element was found. Note that if the element
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000373 # is found, but has no text content, this method returns an
Armin Rigo9ed73062005-12-14 18:10:45 +0000374 # empty string.
375 # @defreturn string
376
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000377 def findtext(self, path, default=None, namespaces=None):
378 return ElementPath.findtext(self, path, default, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000379
380 ##
381 # Finds all matching subelements, by tag name or path.
382 #
383 # @param path What element to look for.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000384 # @keyparam namespaces Optional namespace prefix map.
385 # @return A list or other sequence containing all matching elements,
Armin Rigo9ed73062005-12-14 18:10:45 +0000386 # in document order.
387 # @defreturn list of Element instances
388
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000389 def findall(self, path, namespaces=None):
390 return ElementPath.findall(self, path, namespaces)
391
392 ##
393 # Finds all matching subelements, by tag name or path.
394 #
395 # @param path What element to look for.
396 # @keyparam namespaces Optional namespace prefix map.
397 # @return An iterator or sequence containing all matching elements,
398 # in document order.
399 # @defreturn a generated sequence of Element instances
400
401 def iterfind(self, path, namespaces=None):
402 return ElementPath.iterfind(self, path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000403
404 ##
405 # Resets an element. This function removes all subelements, clears
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000406 # all attributes, and sets the <b>text</b> and <b>tail</b> attributes
407 # to None.
Armin Rigo9ed73062005-12-14 18:10:45 +0000408
409 def clear(self):
410 self.attrib.clear()
411 self._children = []
412 self.text = self.tail = None
413
414 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000415 # Gets an element attribute. Equivalent to <b>attrib.get</b>, but
416 # some implementations may handle this a bit more efficiently.
Armin Rigo9ed73062005-12-14 18:10:45 +0000417 #
418 # @param key What attribute to look for.
419 # @param default What to return if the attribute was not found.
420 # @return The attribute value, or the default value, if the
421 # attribute was not found.
422 # @defreturn string or None
423
424 def get(self, key, default=None):
425 return self.attrib.get(key, default)
426
427 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000428 # Sets an element attribute. Equivalent to <b>attrib[key] = value</b>,
429 # but some implementations may handle this a bit more efficiently.
Armin Rigo9ed73062005-12-14 18:10:45 +0000430 #
431 # @param key What attribute to set.
432 # @param value The attribute value.
433
434 def set(self, key, value):
435 self.attrib[key] = value
436
437 ##
438 # Gets a list of attribute names. The names are returned in an
439 # arbitrary order (just like for an ordinary Python dictionary).
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000440 # Equivalent to <b>attrib.keys()</b>.
Armin Rigo9ed73062005-12-14 18:10:45 +0000441 #
442 # @return A list of element attribute names.
443 # @defreturn list of strings
444
445 def keys(self):
446 return self.attrib.keys()
447
448 ##
449 # Gets element attributes, as a sequence. The attributes are
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000450 # returned in an arbitrary order. Equivalent to <b>attrib.items()</b>.
Armin Rigo9ed73062005-12-14 18:10:45 +0000451 #
452 # @return A list of (name, value) tuples for all attributes.
453 # @defreturn list of (string, string) tuples
454
455 def items(self):
456 return self.attrib.items()
457
458 ##
459 # Creates a tree iterator. The iterator loops over this element
460 # and all subelements, in document order, and returns all elements
461 # with a matching tag.
462 # <p>
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000463 # If the tree structure is modified during iteration, new or removed
464 # elements may or may not be included. To get a stable set, use the
465 # list() function on the iterator, and loop over the resulting list.
Armin Rigo9ed73062005-12-14 18:10:45 +0000466 #
467 # @param tag What tags to look for (default is to return all elements).
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000468 # @return An iterator containing all the matching elements.
469 # @defreturn iterator
Armin Rigo9ed73062005-12-14 18:10:45 +0000470
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000471 def iter(self, tag=None):
Armin Rigo9ed73062005-12-14 18:10:45 +0000472 if tag == "*":
473 tag = None
474 if tag is None or self.tag == tag:
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000475 yield self
476 for e in self._children:
477 for e in e.iter(tag):
478 yield e
479
480 # compatibility
481 def getiterator(self, tag=None):
482 # Change for a DeprecationWarning in 1.4
483 warnings.warn(
484 "This method will be removed in future versions. "
485 "Use 'elem.iter()' or 'list(elem.iter())' instead.",
486 PendingDeprecationWarning, stacklevel=2
487 )
488 return list(self.iter(tag))
489
490 ##
491 # Creates a text iterator. The iterator loops over this element
492 # and all subelements, in document order, and returns all inner
493 # text.
494 #
495 # @return An iterator containing all inner text.
496 # @defreturn iterator
497
498 def itertext(self):
499 tag = self.tag
500 if not isinstance(tag, str) and tag is not None:
501 return
502 if self.text:
503 yield self.text
504 for e in self:
505 for s in e.itertext():
506 yield s
507 if e.tail:
508 yield e.tail
Armin Rigo9ed73062005-12-14 18:10:45 +0000509
510# compatibility
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000511_Element = _ElementInterface = Element
Armin Rigo9ed73062005-12-14 18:10:45 +0000512
513##
514# Subelement factory. This function creates an element instance, and
515# appends it to an existing element.
516# <p>
517# The element name, attribute names, and attribute values can be
518# either 8-bit ASCII strings or Unicode strings.
519#
520# @param parent The parent element.
521# @param tag The subelement name.
522# @param attrib An optional dictionary, containing element attributes.
523# @param **extra Additional attributes, given as keyword arguments.
524# @return An element instance.
525# @defreturn Element
526
527def SubElement(parent, tag, attrib={}, **extra):
528 attrib = attrib.copy()
529 attrib.update(extra)
530 element = parent.makeelement(tag, attrib)
531 parent.append(element)
532 return element
533
534##
535# Comment element factory. This factory function creates a special
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000536# element that will be serialized as an XML comment by the standard
537# serializer.
Armin Rigo9ed73062005-12-14 18:10:45 +0000538# <p>
539# The comment string can be either an 8-bit ASCII string or a Unicode
540# string.
541#
542# @param text A string containing the comment string.
543# @return An element instance, representing a comment.
544# @defreturn Element
545
546def Comment(text=None):
547 element = Element(Comment)
548 element.text = text
549 return element
550
551##
552# PI element factory. This factory function creates a special element
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000553# that will be serialized as an XML processing instruction by the standard
554# serializer.
Armin Rigo9ed73062005-12-14 18:10:45 +0000555#
556# @param target A string containing the PI target.
557# @param text A string containing the PI contents, if any.
558# @return An element instance, representing a PI.
559# @defreturn Element
560
561def ProcessingInstruction(target, text=None):
562 element = Element(ProcessingInstruction)
563 element.text = target
564 if text:
565 element.text = element.text + " " + text
566 return element
567
568PI = ProcessingInstruction
569
570##
571# QName wrapper. This can be used to wrap a QName attribute value, in
572# order to get proper namespace handling on output.
573#
574# @param text A string containing the QName value, in the form {uri}local,
575# or, if the tag argument is given, the URI part of a QName.
576# @param tag Optional tag. If given, the first argument is interpreted as
577# an URI, and this argument is interpreted as a local name.
578# @return An opaque object, representing the QName.
579
580class QName:
581 def __init__(self, text_or_uri, tag=None):
582 if tag:
583 text_or_uri = "{%s}%s" % (text_or_uri, tag)
584 self.text = text_or_uri
585 def __str__(self):
586 return self.text
587 def __hash__(self):
588 return hash(self.text)
Mark Dickinsona56c4672009-01-27 18:17:45 +0000589 def __le__(self, other):
Armin Rigo9ed73062005-12-14 18:10:45 +0000590 if isinstance(other, QName):
Mark Dickinsona56c4672009-01-27 18:17:45 +0000591 return self.text <= other.text
592 return self.text <= other
593 def __lt__(self, other):
594 if isinstance(other, QName):
595 return self.text < other.text
596 return self.text < other
597 def __ge__(self, other):
598 if isinstance(other, QName):
599 return self.text >= other.text
600 return self.text >= other
601 def __gt__(self, other):
602 if isinstance(other, QName):
603 return self.text > other.text
604 return self.text > other
605 def __eq__(self, other):
606 if isinstance(other, QName):
607 return self.text == other.text
608 return self.text == other
609 def __ne__(self, other):
610 if isinstance(other, QName):
611 return self.text != other.text
612 return self.text != other
Armin Rigo9ed73062005-12-14 18:10:45 +0000613
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000614# --------------------------------------------------------------------
615
Armin Rigo9ed73062005-12-14 18:10:45 +0000616##
617# ElementTree wrapper class. This class represents an entire element
618# hierarchy, and adds some extra support for serialization to and from
619# standard XML.
620#
621# @param element Optional root element.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000622# @keyparam file Optional file handle or file name. If given, the
Armin Rigo9ed73062005-12-14 18:10:45 +0000623# tree is initialized with the contents of this XML file.
624
625class ElementTree:
626
627 def __init__(self, element=None, file=None):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000628 # assert element is None or iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000629 self._root = element # first node
630 if file:
631 self.parse(file)
632
633 ##
634 # Gets the root element for this tree.
635 #
636 # @return An element instance.
637 # @defreturn Element
638
639 def getroot(self):
640 return self._root
641
642 ##
643 # Replaces the root element for this tree. This discards the
644 # current contents of the tree, and replaces it with the given
645 # element. Use with care.
646 #
647 # @param element An element instance.
648
649 def _setroot(self, element):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000650 # assert iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000651 self._root = element
652
653 ##
654 # Loads an external XML document into this element tree.
655 #
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000656 # @param source A file name or file object. If a file object is
657 # given, it only has to implement a <b>read(n)</b> method.
658 # @keyparam parser An optional parser instance. If not given, the
659 # standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +0000660 # @return The document root element.
661 # @defreturn Element
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000662 # @exception ParseError If the parser fails to parse the document.
Armin Rigo9ed73062005-12-14 18:10:45 +0000663
664 def parse(self, source, parser=None):
Antoine Pitroue033e062010-10-29 10:38:18 +0000665 close_source = False
Armin Rigo9ed73062005-12-14 18:10:45 +0000666 if not hasattr(source, "read"):
667 source = open(source, "rb")
Antoine Pitroue033e062010-10-29 10:38:18 +0000668 close_source = True
669 try:
670 if not parser:
671 parser = XMLParser(target=TreeBuilder())
672 while 1:
673 data = source.read(65536)
674 if not data:
675 break
676 parser.feed(data)
677 self._root = parser.close()
678 return self._root
679 finally:
680 if close_source:
681 source.close()
Armin Rigo9ed73062005-12-14 18:10:45 +0000682
683 ##
684 # Creates a tree iterator for the root element. The iterator loops
685 # over all elements in this tree, in document order.
686 #
687 # @param tag What tags to look for (default is to return all elements)
688 # @return An iterator.
689 # @defreturn iterator
690
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000691 def iter(self, tag=None):
692 # assert self._root is not None
693 return self._root.iter(tag)
694
695 # compatibility
Armin Rigo9ed73062005-12-14 18:10:45 +0000696 def getiterator(self, tag=None):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000697 # Change for a DeprecationWarning in 1.4
698 warnings.warn(
699 "This method will be removed in future versions. "
700 "Use 'tree.iter()' or 'list(tree.iter())' instead.",
701 PendingDeprecationWarning, stacklevel=2
702 )
703 return list(self.iter(tag))
Armin Rigo9ed73062005-12-14 18:10:45 +0000704
705 ##
706 # Finds the first toplevel element with given tag.
707 # Same as getroot().find(path).
708 #
709 # @param path What element to look for.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000710 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000711 # @return The first matching element, or None if no element was found.
712 # @defreturn Element or None
713
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000714 def find(self, path, namespaces=None):
715 # assert self._root is not None
Armin Rigo9ed73062005-12-14 18:10:45 +0000716 if path[:1] == "/":
717 path = "." + path
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000718 warnings.warn(
719 "This search is broken in 1.3 and earlier, and will be "
720 "fixed in a future version. If you rely on the current "
721 "behaviour, change it to %r" % path,
722 FutureWarning, stacklevel=2
723 )
724 return self._root.find(path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000725
726 ##
727 # Finds the element text for the first toplevel element with given
728 # tag. Same as getroot().findtext(path).
729 #
730 # @param path What toplevel element to look for.
731 # @param default What to return if the element was not found.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000732 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000733 # @return The text content of the first matching element, or the
734 # default value no element was found. Note that if the element
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000735 # is found, but has no text content, this method returns an
Armin Rigo9ed73062005-12-14 18:10:45 +0000736 # empty string.
737 # @defreturn string
738
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000739 def findtext(self, path, default=None, namespaces=None):
740 # assert self._root is not None
Armin Rigo9ed73062005-12-14 18:10:45 +0000741 if path[:1] == "/":
742 path = "." + path
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000743 warnings.warn(
744 "This search is broken in 1.3 and earlier, and will be "
745 "fixed in a future version. If you rely on the current "
746 "behaviour, change it to %r" % path,
747 FutureWarning, stacklevel=2
748 )
749 return self._root.findtext(path, default, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000750
751 ##
752 # Finds all toplevel elements with the given tag.
753 # Same as getroot().findall(path).
754 #
755 # @param path What element to look for.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000756 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000757 # @return A list or iterator containing all matching elements,
758 # in document order.
759 # @defreturn list of Element instances
760
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000761 def findall(self, path, namespaces=None):
762 # assert self._root is not None
Armin Rigo9ed73062005-12-14 18:10:45 +0000763 if path[:1] == "/":
764 path = "." + path
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000765 warnings.warn(
766 "This search is broken in 1.3 and earlier, and will be "
767 "fixed in a future version. If you rely on the current "
768 "behaviour, change it to %r" % path,
769 FutureWarning, stacklevel=2
770 )
771 return self._root.findall(path, namespaces)
772
773 ##
774 # Finds all matching subelements, by tag name or path.
775 # Same as getroot().iterfind(path).
776 #
777 # @param path What element to look for.
778 # @keyparam namespaces Optional namespace prefix map.
779 # @return An iterator or sequence containing all matching elements,
780 # in document order.
781 # @defreturn a generated sequence of Element instances
782
783 def iterfind(self, path, namespaces=None):
784 # assert self._root is not None
785 if path[:1] == "/":
786 path = "." + path
787 warnings.warn(
788 "This search is broken in 1.3 and earlier, and will be "
789 "fixed in a future version. If you rely on the current "
790 "behaviour, change it to %r" % path,
791 FutureWarning, stacklevel=2
792 )
793 return self._root.iterfind(path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000794
795 ##
796 # Writes the element tree to a file, as XML.
797 #
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000798 # @def write(file, **options)
Armin Rigo9ed73062005-12-14 18:10:45 +0000799 # @param file A file name, or a file object opened for writing.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000800 # @param **options Options, given as keyword arguments.
Florent Xiclunac17f1722010-08-08 19:48:29 +0000801 # @keyparam encoding Optional output encoding (default is US-ASCII).
802 # Use "unicode" to return a Unicode string.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000803 # @keyparam method Optional output method ("xml", "html", "text" or
804 # "c14n"; default is "xml").
805 # @keyparam xml_declaration Controls if an XML declaration should
806 # be added to the file. Use False for never, True for always,
Florent Xiclunac17f1722010-08-08 19:48:29 +0000807 # None for only if not US-ASCII or UTF-8 or Unicode. None is default.
Armin Rigo9ed73062005-12-14 18:10:45 +0000808
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000809 def write(self, file_or_filename,
810 # keyword arguments
811 encoding=None,
812 xml_declaration=None,
813 default_namespace=None,
814 method=None):
815 # assert self._root is not None
816 if not method:
817 method = "xml"
818 elif method not in _serialize:
819 # FIXME: raise an ImportError for c14n if ElementC14N is missing?
820 raise ValueError("unknown method %r" % method)
Florent Xiclunac17f1722010-08-08 19:48:29 +0000821 if not encoding:
822 if method == "c14n":
823 encoding = "utf-8"
824 else:
825 encoding = "us-ascii"
826 elif encoding == str: # lxml.etree compatibility.
827 encoding = "unicode"
828 else:
829 encoding = encoding.lower()
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000830 if hasattr(file_or_filename, "write"):
831 file = file_or_filename
Armin Rigo9ed73062005-12-14 18:10:45 +0000832 else:
Florent Xiclunac17f1722010-08-08 19:48:29 +0000833 if encoding != "unicode":
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000834 file = open(file_or_filename, "wb")
Armin Rigo9ed73062005-12-14 18:10:45 +0000835 else:
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000836 file = open(file_or_filename, "w")
Florent Xiclunac17f1722010-08-08 19:48:29 +0000837 if encoding != "unicode":
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000838 def write(text):
839 try:
840 return file.write(text.encode(encoding,
841 "xmlcharrefreplace"))
842 except (TypeError, AttributeError):
843 _raise_serialization_error(text)
844 else:
845 write = file.write
Florent Xiclunac17f1722010-08-08 19:48:29 +0000846 if method == "xml" and (xml_declaration or
847 (xml_declaration is None and
848 encoding not in ("utf-8", "us-ascii", "unicode"))):
849 declared_encoding = encoding
850 if encoding == "unicode":
851 # Retrieve the default encoding for the xml declaration
852 import locale
853 declared_encoding = locale.getpreferredencoding()
854 write("<?xml version='1.0' encoding='%s'?>\n" % declared_encoding)
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000855 if method == "text":
856 _serialize_text(write, self._root)
857 else:
858 qnames, namespaces = _namespaces(self._root, default_namespace)
859 serialize = _serialize[method]
860 serialize(write, self._root, qnames, namespaces)
861 if file_or_filename is not file:
862 file.close()
863
864 def write_c14n(self, file):
865 # lxml.etree compatibility. use output method instead
866 return self.write(file, method="c14n")
Armin Rigo9ed73062005-12-14 18:10:45 +0000867
868# --------------------------------------------------------------------
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000869# serialization support
870
871def _namespaces(elem, default_namespace=None):
872 # identify namespaces used in this tree
873
874 # maps qnames to *encoded* prefix:local names
875 qnames = {None: None}
876
877 # maps uri:s to prefixes
878 namespaces = {}
879 if default_namespace:
880 namespaces[default_namespace] = ""
881
882 def add_qname(qname):
883 # calculate serialized qname representation
884 try:
885 if qname[:1] == "{":
886 uri, tag = qname[1:].rsplit("}", 1)
887 prefix = namespaces.get(uri)
888 if prefix is None:
889 prefix = _namespace_map.get(uri)
890 if prefix is None:
891 prefix = "ns%d" % len(namespaces)
892 if prefix != "xml":
893 namespaces[uri] = prefix
894 if prefix:
895 qnames[qname] = "%s:%s" % (prefix, tag)
896 else:
897 qnames[qname] = tag # default element
898 else:
899 if default_namespace:
900 # FIXME: can this be handled in XML 1.0?
901 raise ValueError(
902 "cannot use non-qualified names with "
903 "default_namespace option"
904 )
905 qnames[qname] = qname
906 except TypeError:
907 _raise_serialization_error(qname)
908
909 # populate qname and namespaces table
910 try:
911 iterate = elem.iter
912 except AttributeError:
913 iterate = elem.getiterator # cET compatibility
914 for elem in iterate():
915 tag = elem.tag
916 if isinstance(tag, QName) and tag.text not in qnames:
917 add_qname(tag.text)
918 elif isinstance(tag, str):
919 if tag not in qnames:
920 add_qname(tag)
921 elif tag is not None and tag is not Comment and tag is not PI:
922 _raise_serialization_error(tag)
923 for key, value in elem.items():
924 if isinstance(key, QName):
925 key = key.text
926 if key not in qnames:
927 add_qname(key)
928 if isinstance(value, QName) and value.text not in qnames:
929 add_qname(value.text)
930 text = elem.text
931 if isinstance(text, QName) and text.text not in qnames:
932 add_qname(text.text)
933 return qnames, namespaces
934
935def _serialize_xml(write, elem, qnames, namespaces):
936 tag = elem.tag
937 text = elem.text
938 if tag is Comment:
939 write("<!--%s-->" % text)
940 elif tag is ProcessingInstruction:
941 write("<?%s?>" % text)
942 else:
943 tag = qnames[tag]
944 if tag is None:
945 if text:
946 write(_escape_cdata(text))
947 for e in elem:
948 _serialize_xml(write, e, qnames, None)
949 else:
950 write("<" + tag)
951 items = list(elem.items())
952 if items or namespaces:
953 if namespaces:
954 for v, k in sorted(namespaces.items(),
955 key=lambda x: x[1]): # sort on prefix
956 if k:
957 k = ":" + k
958 write(" xmlns%s=\"%s\"" % (
959 k,
960 _escape_attrib(v)
961 ))
962 for k, v in sorted(items): # lexical order
963 if isinstance(k, QName):
964 k = k.text
965 if isinstance(v, QName):
966 v = qnames[v.text]
967 else:
968 v = _escape_attrib(v)
969 write(" %s=\"%s\"" % (qnames[k], v))
970 if text or len(elem):
971 write(">")
972 if text:
973 write(_escape_cdata(text))
974 for e in elem:
975 _serialize_xml(write, e, qnames, None)
976 write("</" + tag + ">")
977 else:
978 write(" />")
979 if elem.tail:
980 write(_escape_cdata(elem.tail))
981
982HTML_EMPTY = ("area", "base", "basefont", "br", "col", "frame", "hr",
983 "img", "input", "isindex", "link", "meta" "param")
984
985try:
986 HTML_EMPTY = set(HTML_EMPTY)
987except NameError:
988 pass
989
990def _serialize_html(write, elem, qnames, namespaces):
991 tag = elem.tag
992 text = elem.text
993 if tag is Comment:
994 write("<!--%s-->" % _escape_cdata(text))
995 elif tag is ProcessingInstruction:
996 write("<?%s?>" % _escape_cdata(text))
997 else:
998 tag = qnames[tag]
999 if tag is None:
1000 if text:
1001 write(_escape_cdata(text))
1002 for e in elem:
1003 _serialize_html(write, e, qnames, None)
1004 else:
1005 write("<" + tag)
1006 items = list(elem.items())
1007 if items or namespaces:
1008 if namespaces:
1009 for v, k in sorted(namespaces.items(),
1010 key=lambda x: x[1]): # sort on prefix
1011 if k:
1012 k = ":" + k
1013 write(" xmlns%s=\"%s\"" % (
1014 k,
1015 _escape_attrib(v)
1016 ))
1017 for k, v in sorted(items): # lexical order
1018 if isinstance(k, QName):
1019 k = k.text
1020 if isinstance(v, QName):
1021 v = qnames[v.text]
1022 else:
1023 v = _escape_attrib_html(v)
1024 # FIXME: handle boolean attributes
1025 write(" %s=\"%s\"" % (qnames[k], v))
1026 write(">")
1027 tag = tag.lower()
1028 if text:
1029 if tag == "script" or tag == "style":
1030 write(text)
1031 else:
1032 write(_escape_cdata(text))
1033 for e in elem:
1034 _serialize_html(write, e, qnames, None)
1035 if tag not in HTML_EMPTY:
1036 write("</" + tag + ">")
1037 if elem.tail:
1038 write(_escape_cdata(elem.tail))
1039
1040def _serialize_text(write, elem):
1041 for part in elem.itertext():
1042 write(part)
1043 if elem.tail:
1044 write(elem.tail)
1045
1046_serialize = {
1047 "xml": _serialize_xml,
1048 "html": _serialize_html,
1049 "text": _serialize_text,
1050# this optional method is imported at the end of the module
1051# "c14n": _serialize_c14n,
1052}
Armin Rigo9ed73062005-12-14 18:10:45 +00001053
1054##
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001055# Registers a namespace prefix. The registry is global, and any
1056# existing mapping for either the given prefix or the namespace URI
1057# will be removed.
Armin Rigo9ed73062005-12-14 18:10:45 +00001058#
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001059# @param prefix Namespace prefix.
1060# @param uri Namespace uri. Tags and attributes in this namespace
1061# will be serialized with the given prefix, if at all possible.
1062# @exception ValueError If the prefix is reserved, or is otherwise
1063# invalid.
Armin Rigo9ed73062005-12-14 18:10:45 +00001064
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001065def register_namespace(prefix, uri):
1066 if re.match("ns\d+$", prefix):
1067 raise ValueError("Prefix format reserved for internal use")
1068 for k, v in _namespace_map.items():
1069 if k == uri or v == prefix:
1070 del _namespace_map[k]
1071 _namespace_map[uri] = prefix
1072
1073_namespace_map = {
1074 # "well-known" namespace prefixes
1075 "http://www.w3.org/XML/1998/namespace": "xml",
1076 "http://www.w3.org/1999/xhtml": "html",
1077 "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
1078 "http://schemas.xmlsoap.org/wsdl/": "wsdl",
1079 # xml schema
1080 "http://www.w3.org/2001/XMLSchema": "xs",
1081 "http://www.w3.org/2001/XMLSchema-instance": "xsi",
1082 # dublin core
1083 "http://purl.org/dc/elements/1.1/": "dc",
1084}
1085
1086def _raise_serialization_error(text):
1087 raise TypeError(
1088 "cannot serialize %r (type %s)" % (text, type(text).__name__)
1089 )
1090
1091def _escape_cdata(text):
1092 # escape character data
1093 try:
1094 # it's worth avoiding do-nothing calls for strings that are
1095 # shorter than 500 character, or so. assume that's, by far,
1096 # the most common case in most applications.
1097 if "&" in text:
1098 text = text.replace("&", "&amp;")
1099 if "<" in text:
1100 text = text.replace("<", "&lt;")
1101 if ">" in text:
1102 text = text.replace(">", "&gt;")
1103 return text
1104 except (TypeError, AttributeError):
1105 _raise_serialization_error(text)
1106
1107def _escape_attrib(text):
1108 # escape attribute value
1109 try:
1110 if "&" in text:
1111 text = text.replace("&", "&amp;")
1112 if "<" in text:
1113 text = text.replace("<", "&lt;")
1114 if ">" in text:
1115 text = text.replace(">", "&gt;")
1116 if "\"" in text:
1117 text = text.replace("\"", "&quot;")
1118 if "\n" in text:
1119 text = text.replace("\n", "&#10;")
1120 return text
1121 except (TypeError, AttributeError):
1122 _raise_serialization_error(text)
1123
1124def _escape_attrib_html(text):
1125 # escape attribute value
1126 try:
1127 if "&" in text:
1128 text = text.replace("&", "&amp;")
1129 if ">" in text:
1130 text = text.replace(">", "&gt;")
1131 if "\"" in text:
1132 text = text.replace("\"", "&quot;")
1133 return text
1134 except (TypeError, AttributeError):
1135 _raise_serialization_error(text)
1136
1137# --------------------------------------------------------------------
1138
1139##
1140# Generates a string representation of an XML element, including all
Florent Xiclunac17f1722010-08-08 19:48:29 +00001141# subelements. If encoding is "unicode", the return type is a string;
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001142# otherwise it is a bytes array.
1143#
1144# @param element An Element instance.
Florent Xiclunac17f1722010-08-08 19:48:29 +00001145# @keyparam encoding Optional output encoding (default is US-ASCII).
1146# Use "unicode" to return a Unicode string.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001147# @keyparam method Optional output method ("xml", "html", "text" or
1148# "c14n"; default is "xml").
1149# @return An (optionally) encoded string containing the XML data.
1150# @defreturn string
1151
1152def tostring(element, encoding=None, method=None):
1153 class dummy:
1154 pass
1155 data = []
1156 file = dummy()
1157 file.write = data.append
1158 ElementTree(element).write(file, encoding, method=method)
Florent Xiclunac17f1722010-08-08 19:48:29 +00001159 if encoding in (str, "unicode"):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001160 return "".join(data)
Florent Xiclunac17f1722010-08-08 19:48:29 +00001161 else:
1162 return b"".join(data)
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001163
1164##
1165# Generates a string representation of an XML element, including all
Florent Xiclunac17f1722010-08-08 19:48:29 +00001166# subelements. If encoding is False, the string is returned as a
1167# sequence of string fragments; otherwise it is a sequence of
1168# bytestrings.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001169#
1170# @param element An Element instance.
1171# @keyparam encoding Optional output encoding (default is US-ASCII).
Florent Xiclunac17f1722010-08-08 19:48:29 +00001172# Use "unicode" to return a Unicode string.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001173# @keyparam method Optional output method ("xml", "html", "text" or
1174# "c14n"; default is "xml").
1175# @return A sequence object containing the XML data.
1176# @defreturn sequence
1177# @since 1.3
1178
1179def tostringlist(element, encoding=None, method=None):
1180 class dummy:
1181 pass
1182 data = []
1183 file = dummy()
1184 file.write = data.append
1185 ElementTree(element).write(file, encoding, method=method)
1186 # FIXME: merge small fragments into larger parts
1187 return data
Armin Rigo9ed73062005-12-14 18:10:45 +00001188
1189##
1190# Writes an element tree or element structure to sys.stdout. This
1191# function should be used for debugging only.
1192# <p>
1193# The exact output format is implementation dependent. In this
1194# version, it's written as an ordinary XML file.
1195#
1196# @param elem An element tree or an individual element.
1197
1198def dump(elem):
1199 # debugging
1200 if not isinstance(elem, ElementTree):
1201 elem = ElementTree(elem)
Florent Xiclunac17f1722010-08-08 19:48:29 +00001202 elem.write(sys.stdout, encoding="unicode")
Armin Rigo9ed73062005-12-14 18:10:45 +00001203 tail = elem.getroot().tail
1204 if not tail or tail[-1] != "\n":
1205 sys.stdout.write("\n")
1206
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001207# --------------------------------------------------------------------
1208# parsing
Armin Rigo9ed73062005-12-14 18:10:45 +00001209
1210##
1211# Parses an XML document into an element tree.
1212#
1213# @param source A filename or file object containing XML data.
1214# @param parser An optional parser instance. If not given, the
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001215# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001216# @return An ElementTree instance
1217
1218def parse(source, parser=None):
1219 tree = ElementTree()
1220 tree.parse(source, parser)
1221 return tree
1222
1223##
1224# Parses an XML document into an element tree incrementally, and reports
1225# what's going on to the user.
1226#
1227# @param source A filename or file object containing XML data.
1228# @param events A list of events to report back. If omitted, only "end"
1229# events are reported.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001230# @param parser An optional parser instance. If not given, the
1231# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001232# @return A (event, elem) iterator.
1233
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001234def iterparse(source, events=None, parser=None):
Antoine Pitroue033e062010-10-29 10:38:18 +00001235 close_source = False
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001236 if not hasattr(source, "read"):
1237 source = open(source, "rb")
Antoine Pitroue033e062010-10-29 10:38:18 +00001238 close_source = True
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001239 if not parser:
1240 parser = XMLParser(target=TreeBuilder())
Antoine Pitroue033e062010-10-29 10:38:18 +00001241 return _IterParseIterator(source, events, parser, close_source)
Armin Rigo9ed73062005-12-14 18:10:45 +00001242
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001243class _IterParseIterator:
1244
Antoine Pitroue033e062010-10-29 10:38:18 +00001245 def __init__(self, source, events, parser, close_source=False):
Armin Rigo9ed73062005-12-14 18:10:45 +00001246 self._file = source
Antoine Pitroue033e062010-10-29 10:38:18 +00001247 self._close_file = close_source
Armin Rigo9ed73062005-12-14 18:10:45 +00001248 self._events = []
1249 self._index = 0
1250 self.root = self._root = None
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001251 self._parser = parser
Armin Rigo9ed73062005-12-14 18:10:45 +00001252 # wire up the parser for event reporting
1253 parser = self._parser._parser
1254 append = self._events.append
1255 if events is None:
1256 events = ["end"]
1257 for event in events:
1258 if event == "start":
1259 try:
1260 parser.ordered_attributes = 1
1261 parser.specified_attributes = 1
1262 def handler(tag, attrib_in, event=event, append=append,
1263 start=self._parser._start_list):
1264 append((event, start(tag, attrib_in)))
1265 parser.StartElementHandler = handler
1266 except AttributeError:
1267 def handler(tag, attrib_in, event=event, append=append,
1268 start=self._parser._start):
1269 append((event, start(tag, attrib_in)))
1270 parser.StartElementHandler = handler
1271 elif event == "end":
1272 def handler(tag, event=event, append=append,
1273 end=self._parser._end):
1274 append((event, end(tag)))
1275 parser.EndElementHandler = handler
1276 elif event == "start-ns":
1277 def handler(prefix, uri, event=event, append=append):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001278 append((event, (prefix or "", uri or "")))
Armin Rigo9ed73062005-12-14 18:10:45 +00001279 parser.StartNamespaceDeclHandler = handler
1280 elif event == "end-ns":
1281 def handler(prefix, event=event, append=append):
1282 append((event, None))
1283 parser.EndNamespaceDeclHandler = handler
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001284 else:
1285 raise ValueError("unknown event %r" % event)
Armin Rigo9ed73062005-12-14 18:10:45 +00001286
Georg Brandla18af4e2007-04-21 15:47:16 +00001287 def __next__(self):
Armin Rigo9ed73062005-12-14 18:10:45 +00001288 while 1:
1289 try:
1290 item = self._events[self._index]
1291 except IndexError:
1292 if self._parser is None:
1293 self.root = self._root
Antoine Pitroue033e062010-10-29 10:38:18 +00001294 if self._close_file:
1295 self._file.close()
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001296 raise StopIteration
Armin Rigo9ed73062005-12-14 18:10:45 +00001297 # load event buffer
1298 del self._events[:]
1299 self._index = 0
1300 data = self._file.read(16384)
1301 if data:
1302 self._parser.feed(data)
1303 else:
1304 self._root = self._parser.close()
1305 self._parser = None
1306 else:
1307 self._index = self._index + 1
1308 return item
1309
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001310 def __iter__(self):
1311 return self
Armin Rigo9ed73062005-12-14 18:10:45 +00001312
1313##
1314# Parses an XML document from a string constant. This function can
1315# be used to embed "XML literals" in Python code.
1316#
1317# @param source A string containing XML data.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001318# @param parser An optional parser instance. If not given, the
1319# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001320# @return An Element instance.
1321# @defreturn Element
1322
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001323def XML(text, parser=None):
1324 if not parser:
1325 parser = XMLParser(target=TreeBuilder())
Armin Rigo9ed73062005-12-14 18:10:45 +00001326 parser.feed(text)
1327 return parser.close()
1328
1329##
1330# Parses an XML document from a string constant, and also returns
1331# a dictionary which maps from element id:s to elements.
1332#
1333# @param source A string containing XML data.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001334# @param parser An optional parser instance. If not given, the
1335# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001336# @return A tuple containing an Element instance and a dictionary.
1337# @defreturn (Element, dictionary)
1338
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001339def XMLID(text, parser=None):
1340 if not parser:
1341 parser = XMLParser(target=TreeBuilder())
Armin Rigo9ed73062005-12-14 18:10:45 +00001342 parser.feed(text)
1343 tree = parser.close()
1344 ids = {}
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001345 for elem in tree.iter():
Armin Rigo9ed73062005-12-14 18:10:45 +00001346 id = elem.get("id")
1347 if id:
1348 ids[id] = elem
1349 return tree, ids
1350
1351##
1352# Parses an XML document from a string constant. Same as {@link #XML}.
1353#
1354# @def fromstring(text)
1355# @param source A string containing XML data.
1356# @return An Element instance.
1357# @defreturn Element
1358
1359fromstring = XML
1360
1361##
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001362# Parses an XML document from a sequence of string fragments.
Armin Rigo9ed73062005-12-14 18:10:45 +00001363#
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001364# @param sequence A list or other sequence containing XML data fragments.
1365# @param parser An optional parser instance. If not given, the
1366# standard {@link XMLParser} parser is used.
1367# @return An Element instance.
1368# @defreturn Element
1369# @since 1.3
Armin Rigo9ed73062005-12-14 18:10:45 +00001370
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001371def fromstringlist(sequence, parser=None):
1372 if not parser:
1373 parser = XMLParser(target=TreeBuilder())
1374 for text in sequence:
1375 parser.feed(text)
1376 return parser.close()
1377
1378# --------------------------------------------------------------------
Armin Rigo9ed73062005-12-14 18:10:45 +00001379
1380##
1381# Generic element structure builder. This builder converts a sequence
1382# of {@link #TreeBuilder.start}, {@link #TreeBuilder.data}, and {@link
1383# #TreeBuilder.end} method calls to a well-formed element structure.
1384# <p>
1385# You can use this class to build an element structure using a custom XML
1386# parser, or a parser for some other XML-like format.
1387#
1388# @param element_factory Optional element factory. This factory
1389# is called to create new Element instances, as necessary.
1390
1391class TreeBuilder:
1392
1393 def __init__(self, element_factory=None):
1394 self._data = [] # data collector
1395 self._elem = [] # element stack
1396 self._last = None # last element
1397 self._tail = None # true if we're after an end tag
1398 if element_factory is None:
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001399 element_factory = Element
Armin Rigo9ed73062005-12-14 18:10:45 +00001400 self._factory = element_factory
1401
1402 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001403 # Flushes the builder buffers, and returns the toplevel document
Armin Rigo9ed73062005-12-14 18:10:45 +00001404 # element.
1405 #
1406 # @return An Element instance.
1407 # @defreturn Element
1408
1409 def close(self):
1410 assert len(self._elem) == 0, "missing end tags"
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001411 assert self._last is not None, "missing toplevel element"
Armin Rigo9ed73062005-12-14 18:10:45 +00001412 return self._last
1413
1414 def _flush(self):
1415 if self._data:
1416 if self._last is not None:
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001417 text = "".join(self._data)
Armin Rigo9ed73062005-12-14 18:10:45 +00001418 if self._tail:
1419 assert self._last.tail is None, "internal error (tail)"
1420 self._last.tail = text
1421 else:
1422 assert self._last.text is None, "internal error (text)"
1423 self._last.text = text
1424 self._data = []
1425
1426 ##
1427 # Adds text to the current element.
1428 #
1429 # @param data A string. This should be either an 8-bit string
1430 # containing ASCII text, or a Unicode string.
1431
1432 def data(self, data):
1433 self._data.append(data)
1434
1435 ##
1436 # Opens a new element.
1437 #
1438 # @param tag The element name.
1439 # @param attrib A dictionary containing element attributes.
1440 # @return The opened element.
1441 # @defreturn Element
1442
1443 def start(self, tag, attrs):
1444 self._flush()
1445 self._last = elem = self._factory(tag, attrs)
1446 if self._elem:
1447 self._elem[-1].append(elem)
1448 self._elem.append(elem)
1449 self._tail = 0
1450 return elem
1451
1452 ##
1453 # Closes the current element.
1454 #
1455 # @param tag The element name.
1456 # @return The closed element.
1457 # @defreturn Element
1458
1459 def end(self, tag):
1460 self._flush()
1461 self._last = self._elem.pop()
1462 assert self._last.tag == tag,\
1463 "end tag mismatch (expected %s, got %s)" % (
1464 self._last.tag, tag)
1465 self._tail = 1
1466 return self._last
1467
1468##
1469# Element structure builder for XML source data, based on the
1470# <b>expat</b> parser.
1471#
1472# @keyparam target Target object. If omitted, the builder uses an
1473# instance of the standard {@link #TreeBuilder} class.
1474# @keyparam html Predefine HTML entities. This flag is not supported
1475# by the current implementation.
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001476# @keyparam encoding Optional encoding. If given, the value overrides
1477# the encoding specified in the XML file.
Armin Rigo9ed73062005-12-14 18:10:45 +00001478# @see #ElementTree
1479# @see #TreeBuilder
1480
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001481class XMLParser:
Armin Rigo9ed73062005-12-14 18:10:45 +00001482
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001483 def __init__(self, html=0, target=None, encoding=None):
Armin Rigo9ed73062005-12-14 18:10:45 +00001484 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001485 from xml.parsers import expat
Armin Rigo9ed73062005-12-14 18:10:45 +00001486 except ImportError:
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001487 try:
1488 import pyexpat as expat
1489 except ImportError:
1490 raise ImportError(
1491 "No module named expat; use SimpleXMLTreeBuilder instead"
1492 )
1493 parser = expat.ParserCreate(encoding, "}")
Armin Rigo9ed73062005-12-14 18:10:45 +00001494 if target is None:
1495 target = TreeBuilder()
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001496 # underscored names are provided for compatibility only
1497 self.parser = self._parser = parser
1498 self.target = self._target = target
1499 self._error = expat.error
Armin Rigo9ed73062005-12-14 18:10:45 +00001500 self._names = {} # name memo cache
1501 # callbacks
1502 parser.DefaultHandlerExpand = self._default
1503 parser.StartElementHandler = self._start
1504 parser.EndElementHandler = self._end
1505 parser.CharacterDataHandler = self._data
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001506 # optional callbacks
1507 parser.CommentHandler = self._comment
1508 parser.ProcessingInstructionHandler = self._pi
Armin Rigo9ed73062005-12-14 18:10:45 +00001509 # let expat do the buffering, if supported
1510 try:
1511 self._parser.buffer_text = 1
1512 except AttributeError:
1513 pass
1514 # use new-style attribute handling, if supported
1515 try:
1516 self._parser.ordered_attributes = 1
1517 self._parser.specified_attributes = 1
1518 parser.StartElementHandler = self._start_list
1519 except AttributeError:
1520 pass
Armin Rigo9ed73062005-12-14 18:10:45 +00001521 self._doctype = None
1522 self.entity = {}
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001523 try:
1524 self.version = "Expat %d.%d.%d" % expat.version_info
1525 except AttributeError:
1526 pass # unknown
1527
1528 def _raiseerror(self, value):
1529 err = ParseError(value)
1530 err.code = value.code
1531 err.position = value.lineno, value.offset
1532 raise err
Armin Rigo9ed73062005-12-14 18:10:45 +00001533
Armin Rigo9ed73062005-12-14 18:10:45 +00001534 def _fixname(self, key):
1535 # expand qname, and convert name string to ascii, if possible
1536 try:
1537 name = self._names[key]
1538 except KeyError:
1539 name = key
1540 if "}" in name:
1541 name = "{" + name
Martin v. Löwisf30bb0e2007-07-28 11:40:46 +00001542 self._names[key] = name
Armin Rigo9ed73062005-12-14 18:10:45 +00001543 return name
1544
1545 def _start(self, tag, attrib_in):
1546 fixname = self._fixname
1547 tag = fixname(tag)
1548 attrib = {}
1549 for key, value in attrib_in.items():
Martin v. Löwisf30bb0e2007-07-28 11:40:46 +00001550 attrib[fixname(key)] = value
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001551 return self.target.start(tag, attrib)
Armin Rigo9ed73062005-12-14 18:10:45 +00001552
1553 def _start_list(self, tag, attrib_in):
1554 fixname = self._fixname
1555 tag = fixname(tag)
1556 attrib = {}
1557 if attrib_in:
1558 for i in range(0, len(attrib_in), 2):
Martin v. Löwisf30bb0e2007-07-28 11:40:46 +00001559 attrib[fixname(attrib_in[i])] = attrib_in[i+1]
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001560 return self.target.start(tag, attrib)
Armin Rigo9ed73062005-12-14 18:10:45 +00001561
1562 def _data(self, text):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001563 return self.target.data(text)
Armin Rigo9ed73062005-12-14 18:10:45 +00001564
1565 def _end(self, tag):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001566 return self.target.end(self._fixname(tag))
1567
1568 def _comment(self, data):
1569 try:
1570 comment = self.target.comment
1571 except AttributeError:
1572 pass
1573 else:
1574 return comment(data)
1575
1576 def _pi(self, target, data):
1577 try:
1578 pi = self.target.pi
1579 except AttributeError:
1580 pass
1581 else:
1582 return pi(target, data)
Armin Rigo9ed73062005-12-14 18:10:45 +00001583
1584 def _default(self, text):
1585 prefix = text[:1]
1586 if prefix == "&":
1587 # deal with undefined entities
1588 try:
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001589 self.target.data(self.entity[text[1:-1]])
Armin Rigo9ed73062005-12-14 18:10:45 +00001590 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001591 from xml.parsers import expat
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001592 err = expat.error(
Armin Rigo9ed73062005-12-14 18:10:45 +00001593 "undefined entity %s: line %d, column %d" %
1594 (text, self._parser.ErrorLineNumber,
1595 self._parser.ErrorColumnNumber)
1596 )
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001597 err.code = 11 # XML_ERROR_UNDEFINED_ENTITY
1598 err.lineno = self._parser.ErrorLineNumber
1599 err.offset = self._parser.ErrorColumnNumber
1600 raise err
Armin Rigo9ed73062005-12-14 18:10:45 +00001601 elif prefix == "<" and text[:9] == "<!DOCTYPE":
1602 self._doctype = [] # inside a doctype declaration
1603 elif self._doctype is not None:
1604 # parse doctype contents
1605 if prefix == ">":
1606 self._doctype = None
1607 return
Neal Norwitz9d72bb42007-04-17 08:48:32 +00001608 text = text.strip()
Armin Rigo9ed73062005-12-14 18:10:45 +00001609 if not text:
1610 return
1611 self._doctype.append(text)
1612 n = len(self._doctype)
1613 if n > 2:
1614 type = self._doctype[1]
1615 if type == "PUBLIC" and n == 4:
1616 name, type, pubid, system = self._doctype
1617 elif type == "SYSTEM" and n == 3:
1618 name, type, system = self._doctype
1619 pubid = None
1620 else:
1621 return
1622 if pubid:
1623 pubid = pubid[1:-1]
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001624 if hasattr(self.target, "doctype"):
1625 self.target.doctype(name, pubid, system[1:-1])
1626 elif self.doctype is not self._XMLParser__doctype:
1627 # warn about deprecated call
1628 self._XMLParser__doctype(name, pubid, system[1:-1])
1629 self.doctype(name, pubid, system[1:-1])
Armin Rigo9ed73062005-12-14 18:10:45 +00001630 self._doctype = None
1631
1632 ##
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001633 # (Deprecated) Handles a doctype declaration.
Armin Rigo9ed73062005-12-14 18:10:45 +00001634 #
1635 # @param name Doctype name.
1636 # @param pubid Public identifier.
1637 # @param system System identifier.
1638
1639 def doctype(self, name, pubid, system):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001640 """This method of XMLParser is deprecated."""
1641 warnings.warn(
1642 "This method of XMLParser is deprecated. Define doctype() "
1643 "method on the TreeBuilder target.",
1644 DeprecationWarning,
1645 )
1646
1647 # sentinel, if doctype is redefined in a subclass
1648 __doctype = doctype
Armin Rigo9ed73062005-12-14 18:10:45 +00001649
1650 ##
1651 # Feeds data to the parser.
1652 #
1653 # @param data Encoded data.
1654
1655 def feed(self, data):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001656 try:
1657 self._parser.Parse(data, 0)
1658 except self._error as v:
1659 self._raiseerror(v)
Armin Rigo9ed73062005-12-14 18:10:45 +00001660
1661 ##
1662 # Finishes feeding data to the parser.
1663 #
1664 # @return An element structure.
1665 # @defreturn Element
1666
1667 def close(self):
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001668 try:
1669 self._parser.Parse("", 1) # end of data
1670 except self._error as v:
1671 self._raiseerror(v)
1672 tree = self.target.close()
1673 del self.target, self._parser # get rid of circular references
Armin Rigo9ed73062005-12-14 18:10:45 +00001674 return tree
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001675
1676# compatibility
Florent Xiclunaf15351d2010-03-13 23:24:31 +00001677XMLTreeBuilder = XMLParser
1678
1679# workaround circular import.
1680try:
1681 from ElementC14N import _serialize_c14n
1682 _serialize["c14n"] = _serialize_c14n
1683except ImportError:
1684 pass