blob: cd33cd08a6c524ff160fcf37cc0702179d8e13e9 [file] [log] [blame]
Armin Rigo9ed73062005-12-14 18:10:45 +00001#
2# ElementTree
Florent Xicluna3e8c1892010-03-11 14:36:19 +00003# $Id: ElementTree.py 3440 2008-07-18 14:45:01Z fredrik $
Armin Rigo9ed73062005-12-14 18:10:45 +00004#
Florent Xicluna3e8c1892010-03-11 14:36:19 +00005# light-weight XML support for Python 2.3 and later.
Armin Rigo9ed73062005-12-14 18:10:45 +00006#
Florent Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +000062 "fromstring", "fromstringlist",
Armin Rigo9ed73062005-12-14 18:10:45 +000063 "iselement", "iterparse",
Florent Xicluna3e8c1892010-03-11 14:36:19 +000064 "parse", "ParseError",
Armin Rigo9ed73062005-12-14 18:10:45 +000065 "PI", "ProcessingInstruction",
66 "QName",
67 "SubElement",
Florent Xicluna3e8c1892010-03-11 14:36:19 +000068 "tostring", "tostringlist",
Armin Rigo9ed73062005-12-14 18:10:45 +000069 "TreeBuilder",
Florent Xicluna3e8c1892010-03-11 14:36:19 +000070 "VERSION",
71 "XML",
Fredrik Lundhbf84e542006-07-06 12:29:24 +000072 "XMLParser", "XMLTreeBuilder",
Armin Rigo9ed73062005-12-14 18:10:45 +000073 ]
74
Florent Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +000099import sys
100import re
101import warnings
Armin Rigo9ed73062005-12-14 18:10:45 +0000102
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000103
104class _SimpleElementPath(object):
Armin Rigo9ed73062005-12-14 18:10:45 +0000105 # emulate pre-1.2 find/findtext/findall behaviour
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000106 def find(self, element, tag, namespaces=None):
Armin Rigo9ed73062005-12-14 18:10:45 +0000107 for elem in element:
108 if elem.tag == tag:
109 return elem
110 return None
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000111 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):
Armin Rigo9ed73062005-12-14 18:10:45 +0000117 if tag[:3] == ".//":
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000118 for elem in element.iter(tag[3:]):
119 yield elem
Armin Rigo9ed73062005-12-14 18:10:45 +0000120 for elem in element:
121 if elem.tag == tag:
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000122 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
126try:
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000127 from . import ElementPath
Armin Rigo9ed73062005-12-14 18:10:45 +0000128except ImportError:
Armin Rigo9ed73062005-12-14 18:10:45 +0000129 ElementPath = _SimpleElementPath()
130
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000131##
132# Parser error. This is a subclass of <b>SyntaxError</b>.
133# <p>
134# 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.
Armin Rigo9ed73062005-12-14 18:10:45 +0000137
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000138class ParseError(SyntaxError):
139 pass
140
141# --------------------------------------------------------------------
Armin Rigo9ed73062005-12-14 18:10:45 +0000142
143##
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000144# Checks if an object appears to be a valid element object.
Armin Rigo9ed73062005-12-14 18:10:45 +0000145#
Florent Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +0000171class Element(object):
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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +0000225 return self.__class__(tag, attrib)
Armin Rigo9ed73062005-12-14 18:10:45 +0000226
227 ##
Florent Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +0000250 def __nonzero__(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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +0000301 # assert iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000302 self._children.append(element)
303
304 ##
Florent Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +0000336 # assert iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000337 self._children.remove(element)
338
339 ##
Florent Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +0000468 # @return An iterator containing all the matching elements.
469 # @defreturn iterator
Armin Rigo9ed73062005-12-14 18:10:45 +0000470
Florent Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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, basestring) 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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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 Xicluna3e8c1892010-03-11 14:36:19 +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
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000580class QName(object):
Armin Rigo9ed73062005-12-14 18:10:45 +0000581 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)
589 def __cmp__(self, other):
590 if isinstance(other, QName):
591 return cmp(self.text, other.text)
592 return cmp(self.text, other)
593
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000594# --------------------------------------------------------------------
595
Armin Rigo9ed73062005-12-14 18:10:45 +0000596##
597# ElementTree wrapper class. This class represents an entire element
598# hierarchy, and adds some extra support for serialization to and from
599# standard XML.
600#
601# @param element Optional root element.
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000602# @keyparam file Optional file handle or file name. If given, the
Armin Rigo9ed73062005-12-14 18:10:45 +0000603# tree is initialized with the contents of this XML file.
604
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000605class ElementTree(object):
Armin Rigo9ed73062005-12-14 18:10:45 +0000606
607 def __init__(self, element=None, file=None):
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000608 # assert element is None or iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000609 self._root = element # first node
610 if file:
611 self.parse(file)
612
613 ##
614 # Gets the root element for this tree.
615 #
616 # @return An element instance.
617 # @defreturn Element
618
619 def getroot(self):
620 return self._root
621
622 ##
623 # Replaces the root element for this tree. This discards the
624 # current contents of the tree, and replaces it with the given
625 # element. Use with care.
626 #
627 # @param element An element instance.
628
629 def _setroot(self, element):
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000630 # assert iselement(element)
Armin Rigo9ed73062005-12-14 18:10:45 +0000631 self._root = element
632
633 ##
634 # Loads an external XML document into this element tree.
635 #
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000636 # @param source A file name or file object. If a file object is
637 # given, it only has to implement a <b>read(n)</b> method.
638 # @keyparam parser An optional parser instance. If not given, the
639 # standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +0000640 # @return The document root element.
641 # @defreturn Element
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000642 # @exception ParseError If the parser fails to parse the document.
Armin Rigo9ed73062005-12-14 18:10:45 +0000643
644 def parse(self, source, parser=None):
Florent Xicluna67d5d0e2011-10-29 03:38:56 +0200645 close_source = False
Armin Rigo9ed73062005-12-14 18:10:45 +0000646 if not hasattr(source, "read"):
647 source = open(source, "rb")
Florent Xicluna67d5d0e2011-10-29 03:38:56 +0200648 close_source = True
649 try:
650 if not parser:
651 parser = XMLParser(target=TreeBuilder())
652 while 1:
653 data = source.read(65536)
654 if not data:
655 break
656 parser.feed(data)
657 self._root = parser.close()
658 return self._root
659 finally:
660 if close_source:
661 source.close()
Armin Rigo9ed73062005-12-14 18:10:45 +0000662
663 ##
664 # Creates a tree iterator for the root element. The iterator loops
665 # over all elements in this tree, in document order.
666 #
667 # @param tag What tags to look for (default is to return all elements)
668 # @return An iterator.
669 # @defreturn iterator
670
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000671 def iter(self, tag=None):
672 # assert self._root is not None
673 return self._root.iter(tag)
674
675 # compatibility
Armin Rigo9ed73062005-12-14 18:10:45 +0000676 def getiterator(self, tag=None):
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000677 # Change for a DeprecationWarning in 1.4
678 warnings.warn(
679 "This method will be removed in future versions. "
680 "Use 'tree.iter()' or 'list(tree.iter())' instead.",
681 PendingDeprecationWarning, stacklevel=2
682 )
683 return list(self.iter(tag))
Armin Rigo9ed73062005-12-14 18:10:45 +0000684
685 ##
686 # Finds the first toplevel element with given tag.
687 # Same as getroot().find(path).
688 #
689 # @param path What element to look for.
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000690 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000691 # @return The first matching element, or None if no element was found.
692 # @defreturn Element or None
693
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000694 def find(self, path, namespaces=None):
695 # assert self._root is not None
Armin Rigo9ed73062005-12-14 18:10:45 +0000696 if path[:1] == "/":
697 path = "." + path
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000698 warnings.warn(
699 "This search is broken in 1.3 and earlier, and will be "
700 "fixed in a future version. If you rely on the current "
701 "behaviour, change it to %r" % path,
702 FutureWarning, stacklevel=2
703 )
704 return self._root.find(path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000705
706 ##
707 # Finds the element text for the first toplevel element with given
708 # tag. Same as getroot().findtext(path).
709 #
710 # @param path What toplevel element to look for.
711 # @param default What to return if the element was not found.
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000712 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000713 # @return The text content of the first matching element, or the
714 # default value no element was found. Note that if the element
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000715 # is found, but has no text content, this method returns an
Armin Rigo9ed73062005-12-14 18:10:45 +0000716 # empty string.
717 # @defreturn string
718
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000719 def findtext(self, path, default=None, namespaces=None):
720 # assert self._root is not None
Armin Rigo9ed73062005-12-14 18:10:45 +0000721 if path[:1] == "/":
722 path = "." + path
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000723 warnings.warn(
724 "This search is broken in 1.3 and earlier, and will be "
725 "fixed in a future version. If you rely on the current "
726 "behaviour, change it to %r" % path,
727 FutureWarning, stacklevel=2
728 )
729 return self._root.findtext(path, default, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000730
731 ##
732 # Finds all toplevel elements with the given tag.
733 # Same as getroot().findall(path).
734 #
735 # @param path What element to look for.
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000736 # @keyparam namespaces Optional namespace prefix map.
Armin Rigo9ed73062005-12-14 18:10:45 +0000737 # @return A list or iterator containing all matching elements,
738 # in document order.
739 # @defreturn list of Element instances
740
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000741 def findall(self, path, namespaces=None):
742 # assert self._root is not None
Armin Rigo9ed73062005-12-14 18:10:45 +0000743 if path[:1] == "/":
744 path = "." + path
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000745 warnings.warn(
746 "This search is broken in 1.3 and earlier, and will be "
747 "fixed in a future version. If you rely on the current "
748 "behaviour, change it to %r" % path,
749 FutureWarning, stacklevel=2
750 )
751 return self._root.findall(path, namespaces)
752
753 ##
754 # Finds all matching subelements, by tag name or path.
755 # Same as getroot().iterfind(path).
756 #
757 # @param path What element to look for.
758 # @keyparam namespaces Optional namespace prefix map.
759 # @return An iterator or sequence containing all matching elements,
760 # in document order.
761 # @defreturn a generated sequence of Element instances
762
763 def iterfind(self, path, namespaces=None):
764 # assert self._root is not None
765 if path[:1] == "/":
766 path = "." + path
767 warnings.warn(
768 "This search is broken in 1.3 and earlier, and will be "
769 "fixed in a future version. If you rely on the current "
770 "behaviour, change it to %r" % path,
771 FutureWarning, stacklevel=2
772 )
773 return self._root.iterfind(path, namespaces)
Armin Rigo9ed73062005-12-14 18:10:45 +0000774
775 ##
776 # Writes the element tree to a file, as XML.
777 #
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000778 # @def write(file, **options)
Armin Rigo9ed73062005-12-14 18:10:45 +0000779 # @param file A file name, or a file object opened for writing.
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000780 # @param **options Options, given as keyword arguments.
781 # @keyparam encoding Optional output encoding (default is US-ASCII).
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000782 # @keyparam xml_declaration Controls if an XML declaration should
783 # be added to the file. Use False for never, True for always,
784 # None for only if not US-ASCII or UTF-8. None is default.
Serhiy Storchaka3d4a02a2013-01-13 21:57:14 +0200785 # @keyparam default_namespace Sets the default XML namespace (for "xmlns").
786 # @keyparam method Optional output method ("xml", "html", "text" or
787 # "c14n"; default is "xml").
Armin Rigo9ed73062005-12-14 18:10:45 +0000788
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000789 def write(self, file_or_filename,
790 # keyword arguments
791 encoding=None,
792 xml_declaration=None,
793 default_namespace=None,
794 method=None):
795 # assert self._root is not None
796 if not method:
797 method = "xml"
798 elif method not in _serialize:
799 # FIXME: raise an ImportError for c14n if ElementC14N is missing?
800 raise ValueError("unknown method %r" % method)
801 if hasattr(file_or_filename, "write"):
802 file = file_or_filename
Armin Rigo9ed73062005-12-14 18:10:45 +0000803 else:
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000804 file = open(file_or_filename, "wb")
805 write = file.write
806 if not encoding:
807 if method == "c14n":
808 encoding = "utf-8"
Armin Rigo9ed73062005-12-14 18:10:45 +0000809 else:
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000810 encoding = "us-ascii"
811 elif xml_declaration or (xml_declaration is None and
812 encoding not in ("utf-8", "us-ascii")):
813 if method == "xml":
814 write("<?xml version='1.0' encoding='%s'?>\n" % encoding)
815 if method == "text":
816 _serialize_text(write, self._root, encoding)
817 else:
818 qnames, namespaces = _namespaces(
819 self._root, encoding, default_namespace
820 )
821 serialize = _serialize[method]
822 serialize(write, self._root, encoding, qnames, namespaces)
823 if file_or_filename is not file:
824 file.close()
825
826 def write_c14n(self, file):
827 # lxml.etree compatibility. use output method instead
828 return self.write(file, method="c14n")
Armin Rigo9ed73062005-12-14 18:10:45 +0000829
830# --------------------------------------------------------------------
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000831# serialization support
832
833def _namespaces(elem, encoding, default_namespace=None):
834 # identify namespaces used in this tree
835
836 # maps qnames to *encoded* prefix:local names
837 qnames = {None: None}
838
839 # maps uri:s to prefixes
840 namespaces = {}
841 if default_namespace:
842 namespaces[default_namespace] = ""
843
844 def encode(text):
845 return text.encode(encoding)
846
847 def add_qname(qname):
848 # calculate serialized qname representation
849 try:
850 if qname[:1] == "{":
851 uri, tag = qname[1:].rsplit("}", 1)
852 prefix = namespaces.get(uri)
853 if prefix is None:
854 prefix = _namespace_map.get(uri)
855 if prefix is None:
856 prefix = "ns%d" % len(namespaces)
857 if prefix != "xml":
858 namespaces[uri] = prefix
859 if prefix:
860 qnames[qname] = encode("%s:%s" % (prefix, tag))
861 else:
862 qnames[qname] = encode(tag) # default element
863 else:
864 if default_namespace:
865 # FIXME: can this be handled in XML 1.0?
866 raise ValueError(
867 "cannot use non-qualified names with "
868 "default_namespace option"
869 )
870 qnames[qname] = encode(qname)
871 except TypeError:
872 _raise_serialization_error(qname)
873
874 # populate qname and namespaces table
875 try:
876 iterate = elem.iter
877 except AttributeError:
878 iterate = elem.getiterator # cET compatibility
879 for elem in iterate():
880 tag = elem.tag
Senthil Kumaran80860382010-11-09 02:49:26 +0000881 if isinstance(tag, QName):
882 if tag.text not in qnames:
883 add_qname(tag.text)
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000884 elif isinstance(tag, basestring):
885 if tag not in qnames:
886 add_qname(tag)
887 elif tag is not None and tag is not Comment and tag is not PI:
888 _raise_serialization_error(tag)
889 for key, value in elem.items():
890 if isinstance(key, QName):
891 key = key.text
892 if key not in qnames:
893 add_qname(key)
894 if isinstance(value, QName) and value.text not in qnames:
895 add_qname(value.text)
896 text = elem.text
897 if isinstance(text, QName) and text.text not in qnames:
898 add_qname(text.text)
899 return qnames, namespaces
900
901def _serialize_xml(write, elem, encoding, qnames, namespaces):
902 tag = elem.tag
903 text = elem.text
904 if tag is Comment:
905 write("<!--%s-->" % _encode(text, encoding))
906 elif tag is ProcessingInstruction:
907 write("<?%s?>" % _encode(text, encoding))
908 else:
909 tag = qnames[tag]
910 if tag is None:
911 if text:
912 write(_escape_cdata(text, encoding))
913 for e in elem:
914 _serialize_xml(write, e, encoding, qnames, None)
915 else:
916 write("<" + tag)
917 items = elem.items()
918 if items or namespaces:
919 if namespaces:
920 for v, k in sorted(namespaces.items(),
921 key=lambda x: x[1]): # sort on prefix
922 if k:
923 k = ":" + k
924 write(" xmlns%s=\"%s\"" % (
925 k.encode(encoding),
926 _escape_attrib(v, encoding)
927 ))
928 for k, v in sorted(items): # lexical order
929 if isinstance(k, QName):
930 k = k.text
931 if isinstance(v, QName):
932 v = qnames[v.text]
933 else:
934 v = _escape_attrib(v, encoding)
935 write(" %s=\"%s\"" % (qnames[k], v))
936 if text or len(elem):
937 write(">")
938 if text:
939 write(_escape_cdata(text, encoding))
940 for e in elem:
941 _serialize_xml(write, e, encoding, qnames, None)
942 write("</" + tag + ">")
943 else:
944 write(" />")
945 if elem.tail:
946 write(_escape_cdata(elem.tail, encoding))
947
948HTML_EMPTY = ("area", "base", "basefont", "br", "col", "frame", "hr",
Ezio Melotti6d6fb3a2012-09-19 08:11:03 +0300949 "img", "input", "isindex", "link", "meta", "param")
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000950
951try:
952 HTML_EMPTY = set(HTML_EMPTY)
953except NameError:
954 pass
955
956def _serialize_html(write, elem, encoding, qnames, namespaces):
957 tag = elem.tag
958 text = elem.text
959 if tag is Comment:
960 write("<!--%s-->" % _escape_cdata(text, encoding))
961 elif tag is ProcessingInstruction:
962 write("<?%s?>" % _escape_cdata(text, encoding))
963 else:
964 tag = qnames[tag]
965 if tag is None:
966 if text:
967 write(_escape_cdata(text, encoding))
968 for e in elem:
969 _serialize_html(write, e, encoding, qnames, None)
970 else:
971 write("<" + tag)
972 items = elem.items()
973 if items or namespaces:
974 if namespaces:
975 for v, k in sorted(namespaces.items(),
976 key=lambda x: x[1]): # sort on prefix
977 if k:
978 k = ":" + k
979 write(" xmlns%s=\"%s\"" % (
980 k.encode(encoding),
981 _escape_attrib(v, encoding)
982 ))
983 for k, v in sorted(items): # lexical order
984 if isinstance(k, QName):
985 k = k.text
986 if isinstance(v, QName):
987 v = qnames[v.text]
988 else:
989 v = _escape_attrib_html(v, encoding)
990 # FIXME: handle boolean attributes
991 write(" %s=\"%s\"" % (qnames[k], v))
992 write(">")
993 tag = tag.lower()
994 if text:
995 if tag == "script" or tag == "style":
996 write(_encode(text, encoding))
997 else:
998 write(_escape_cdata(text, encoding))
999 for e in elem:
1000 _serialize_html(write, e, encoding, qnames, None)
1001 if tag not in HTML_EMPTY:
1002 write("</" + tag + ">")
1003 if elem.tail:
1004 write(_escape_cdata(elem.tail, encoding))
1005
1006def _serialize_text(write, elem, encoding):
1007 for part in elem.itertext():
1008 write(part.encode(encoding))
1009 if elem.tail:
1010 write(elem.tail.encode(encoding))
1011
1012_serialize = {
1013 "xml": _serialize_xml,
1014 "html": _serialize_html,
1015 "text": _serialize_text,
1016# this optional method is imported at the end of the module
1017# "c14n": _serialize_c14n,
1018}
Armin Rigo9ed73062005-12-14 18:10:45 +00001019
1020##
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001021# Registers a namespace prefix. The registry is global, and any
1022# existing mapping for either the given prefix or the namespace URI
1023# will be removed.
Armin Rigo9ed73062005-12-14 18:10:45 +00001024#
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001025# @param prefix Namespace prefix.
1026# @param uri Namespace uri. Tags and attributes in this namespace
1027# will be serialized with the given prefix, if at all possible.
1028# @exception ValueError If the prefix is reserved, or is otherwise
1029# invalid.
Armin Rigo9ed73062005-12-14 18:10:45 +00001030
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001031def register_namespace(prefix, uri):
1032 if re.match("ns\d+$", prefix):
1033 raise ValueError("Prefix format reserved for internal use")
1034 for k, v in _namespace_map.items():
1035 if k == uri or v == prefix:
1036 del _namespace_map[k]
1037 _namespace_map[uri] = prefix
1038
1039_namespace_map = {
1040 # "well-known" namespace prefixes
1041 "http://www.w3.org/XML/1998/namespace": "xml",
1042 "http://www.w3.org/1999/xhtml": "html",
1043 "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
1044 "http://schemas.xmlsoap.org/wsdl/": "wsdl",
1045 # xml schema
1046 "http://www.w3.org/2001/XMLSchema": "xs",
1047 "http://www.w3.org/2001/XMLSchema-instance": "xsi",
1048 # dublin core
1049 "http://purl.org/dc/elements/1.1/": "dc",
1050}
1051
1052def _raise_serialization_error(text):
1053 raise TypeError(
1054 "cannot serialize %r (type %s)" % (text, type(text).__name__)
1055 )
1056
1057def _encode(text, encoding):
1058 try:
1059 return text.encode(encoding, "xmlcharrefreplace")
1060 except (TypeError, AttributeError):
1061 _raise_serialization_error(text)
1062
1063def _escape_cdata(text, encoding):
1064 # escape character data
1065 try:
1066 # it's worth avoiding do-nothing calls for strings that are
1067 # shorter than 500 character, or so. assume that's, by far,
1068 # the most common case in most applications.
1069 if "&" in text:
1070 text = text.replace("&", "&amp;")
1071 if "<" in text:
1072 text = text.replace("<", "&lt;")
1073 if ">" in text:
1074 text = text.replace(">", "&gt;")
1075 return text.encode(encoding, "xmlcharrefreplace")
1076 except (TypeError, AttributeError):
1077 _raise_serialization_error(text)
1078
1079def _escape_attrib(text, encoding):
1080 # escape attribute value
1081 try:
1082 if "&" in text:
1083 text = text.replace("&", "&amp;")
1084 if "<" in text:
1085 text = text.replace("<", "&lt;")
1086 if ">" in text:
1087 text = text.replace(">", "&gt;")
1088 if "\"" in text:
1089 text = text.replace("\"", "&quot;")
1090 if "\n" in text:
1091 text = text.replace("\n", "&#10;")
1092 return text.encode(encoding, "xmlcharrefreplace")
1093 except (TypeError, AttributeError):
1094 _raise_serialization_error(text)
1095
1096def _escape_attrib_html(text, encoding):
1097 # escape attribute value
1098 try:
1099 if "&" in text:
1100 text = text.replace("&", "&amp;")
1101 if ">" in text:
1102 text = text.replace(">", "&gt;")
1103 if "\"" in text:
1104 text = text.replace("\"", "&quot;")
1105 return text.encode(encoding, "xmlcharrefreplace")
1106 except (TypeError, AttributeError):
1107 _raise_serialization_error(text)
1108
1109# --------------------------------------------------------------------
1110
1111##
1112# Generates a string representation of an XML element, including all
1113# subelements.
1114#
1115# @param element An Element instance.
1116# @keyparam encoding Optional output encoding (default is US-ASCII).
1117# @keyparam method Optional output method ("xml", "html", "text" or
1118# "c14n"; default is "xml").
1119# @return An encoded string containing the XML data.
1120# @defreturn string
1121
1122def tostring(element, encoding=None, method=None):
1123 class dummy:
1124 pass
1125 data = []
1126 file = dummy()
1127 file.write = data.append
1128 ElementTree(element).write(file, encoding, method=method)
1129 return "".join(data)
1130
1131##
1132# Generates a string representation of an XML element, including all
1133# subelements. The string is returned as a sequence of string fragments.
1134#
1135# @param element An Element instance.
1136# @keyparam encoding Optional output encoding (default is US-ASCII).
1137# @keyparam method Optional output method ("xml", "html", "text" or
1138# "c14n"; default is "xml").
1139# @return A sequence object containing the XML data.
1140# @defreturn sequence
1141# @since 1.3
1142
1143def tostringlist(element, encoding=None, method=None):
1144 class dummy:
1145 pass
1146 data = []
1147 file = dummy()
1148 file.write = data.append
1149 ElementTree(element).write(file, encoding, method=method)
1150 # FIXME: merge small fragments into larger parts
1151 return data
Armin Rigo9ed73062005-12-14 18:10:45 +00001152
1153##
1154# Writes an element tree or element structure to sys.stdout. This
1155# function should be used for debugging only.
1156# <p>
1157# The exact output format is implementation dependent. In this
1158# version, it's written as an ordinary XML file.
1159#
1160# @param elem An element tree or an individual element.
1161
1162def dump(elem):
1163 # debugging
1164 if not isinstance(elem, ElementTree):
1165 elem = ElementTree(elem)
1166 elem.write(sys.stdout)
1167 tail = elem.getroot().tail
1168 if not tail or tail[-1] != "\n":
1169 sys.stdout.write("\n")
1170
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001171# --------------------------------------------------------------------
1172# parsing
Armin Rigo9ed73062005-12-14 18:10:45 +00001173
1174##
1175# Parses an XML document into an element tree.
1176#
1177# @param source A filename or file object containing XML data.
1178# @param parser An optional parser instance. If not given, the
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001179# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001180# @return An ElementTree instance
1181
1182def parse(source, parser=None):
1183 tree = ElementTree()
1184 tree.parse(source, parser)
1185 return tree
1186
1187##
1188# Parses an XML document into an element tree incrementally, and reports
1189# what's going on to the user.
1190#
1191# @param source A filename or file object containing XML data.
1192# @param events A list of events to report back. If omitted, only "end"
1193# events are reported.
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001194# @param parser An optional parser instance. If not given, the
1195# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001196# @return A (event, elem) iterator.
1197
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001198def iterparse(source, events=None, parser=None):
Florent Xicluna67d5d0e2011-10-29 03:38:56 +02001199 close_source = False
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001200 if not hasattr(source, "read"):
1201 source = open(source, "rb")
Florent Xicluna67d5d0e2011-10-29 03:38:56 +02001202 close_source = True
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001203 if not parser:
1204 parser = XMLParser(target=TreeBuilder())
Florent Xicluna67d5d0e2011-10-29 03:38:56 +02001205 return _IterParseIterator(source, events, parser, close_source)
Armin Rigo9ed73062005-12-14 18:10:45 +00001206
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001207class _IterParseIterator(object):
1208
Florent Xicluna67d5d0e2011-10-29 03:38:56 +02001209 def __init__(self, source, events, parser, close_source=False):
Armin Rigo9ed73062005-12-14 18:10:45 +00001210 self._file = source
Florent Xicluna67d5d0e2011-10-29 03:38:56 +02001211 self._close_file = close_source
Armin Rigo9ed73062005-12-14 18:10:45 +00001212 self._events = []
1213 self._index = 0
Florent Xicluna0965ee22011-11-01 23:34:41 +01001214 self._error = None
Armin Rigo9ed73062005-12-14 18:10:45 +00001215 self.root = self._root = None
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001216 self._parser = parser
Armin Rigo9ed73062005-12-14 18:10:45 +00001217 # wire up the parser for event reporting
1218 parser = self._parser._parser
1219 append = self._events.append
1220 if events is None:
1221 events = ["end"]
1222 for event in events:
1223 if event == "start":
1224 try:
1225 parser.ordered_attributes = 1
1226 parser.specified_attributes = 1
1227 def handler(tag, attrib_in, event=event, append=append,
1228 start=self._parser._start_list):
1229 append((event, start(tag, attrib_in)))
1230 parser.StartElementHandler = handler
1231 except AttributeError:
1232 def handler(tag, attrib_in, event=event, append=append,
1233 start=self._parser._start):
1234 append((event, start(tag, attrib_in)))
1235 parser.StartElementHandler = handler
1236 elif event == "end":
1237 def handler(tag, event=event, append=append,
1238 end=self._parser._end):
1239 append((event, end(tag)))
1240 parser.EndElementHandler = handler
1241 elif event == "start-ns":
1242 def handler(prefix, uri, event=event, append=append):
1243 try:
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001244 uri = (uri or "").encode("ascii")
Armin Rigo9ed73062005-12-14 18:10:45 +00001245 except UnicodeError:
1246 pass
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001247 append((event, (prefix or "", uri or "")))
Armin Rigo9ed73062005-12-14 18:10:45 +00001248 parser.StartNamespaceDeclHandler = handler
1249 elif event == "end-ns":
1250 def handler(prefix, event=event, append=append):
1251 append((event, None))
1252 parser.EndNamespaceDeclHandler = handler
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001253 else:
1254 raise ValueError("unknown event %r" % event)
Armin Rigo9ed73062005-12-14 18:10:45 +00001255
1256 def next(self):
1257 while 1:
1258 try:
1259 item = self._events[self._index]
Florent Xicluna0965ee22011-11-01 23:34:41 +01001260 self._index += 1
Armin Rigo9ed73062005-12-14 18:10:45 +00001261 return item
Florent Xicluna0965ee22011-11-01 23:34:41 +01001262 except IndexError:
1263 pass
1264 if self._error:
1265 e = self._error
1266 self._error = None
1267 raise e
1268 if self._parser is None:
1269 self.root = self._root
1270 if self._close_file:
1271 self._file.close()
1272 raise StopIteration
1273 # load event buffer
1274 del self._events[:]
1275 self._index = 0
1276 data = self._file.read(16384)
1277 if data:
1278 try:
1279 self._parser.feed(data)
1280 except SyntaxError as exc:
1281 self._error = exc
1282 else:
1283 self._root = self._parser.close()
1284 self._parser = None
Armin Rigo9ed73062005-12-14 18:10:45 +00001285
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001286 def __iter__(self):
1287 return self
Armin Rigo9ed73062005-12-14 18:10:45 +00001288
1289##
1290# Parses an XML document from a string constant. This function can
1291# be used to embed "XML literals" in Python code.
1292#
1293# @param source A string containing XML data.
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001294# @param parser An optional parser instance. If not given, the
1295# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001296# @return An Element instance.
1297# @defreturn Element
1298
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001299def XML(text, parser=None):
1300 if not parser:
1301 parser = XMLParser(target=TreeBuilder())
Armin Rigo9ed73062005-12-14 18:10:45 +00001302 parser.feed(text)
1303 return parser.close()
1304
1305##
1306# Parses an XML document from a string constant, and also returns
1307# a dictionary which maps from element id:s to elements.
1308#
1309# @param source A string containing XML data.
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001310# @param parser An optional parser instance. If not given, the
1311# standard {@link XMLParser} parser is used.
Armin Rigo9ed73062005-12-14 18:10:45 +00001312# @return A tuple containing an Element instance and a dictionary.
1313# @defreturn (Element, dictionary)
1314
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001315def XMLID(text, parser=None):
1316 if not parser:
1317 parser = XMLParser(target=TreeBuilder())
Armin Rigo9ed73062005-12-14 18:10:45 +00001318 parser.feed(text)
1319 tree = parser.close()
1320 ids = {}
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001321 for elem in tree.iter():
Armin Rigo9ed73062005-12-14 18:10:45 +00001322 id = elem.get("id")
1323 if id:
1324 ids[id] = elem
1325 return tree, ids
1326
1327##
1328# Parses an XML document from a string constant. Same as {@link #XML}.
1329#
1330# @def fromstring(text)
1331# @param source A string containing XML data.
1332# @return An Element instance.
1333# @defreturn Element
1334
1335fromstring = XML
1336
1337##
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001338# Parses an XML document from a sequence of string fragments.
Armin Rigo9ed73062005-12-14 18:10:45 +00001339#
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001340# @param sequence A list or other sequence containing XML data fragments.
1341# @param parser An optional parser instance. If not given, the
1342# standard {@link XMLParser} parser is used.
1343# @return An Element instance.
1344# @defreturn Element
1345# @since 1.3
Armin Rigo9ed73062005-12-14 18:10:45 +00001346
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001347def fromstringlist(sequence, parser=None):
1348 if not parser:
1349 parser = XMLParser(target=TreeBuilder())
1350 for text in sequence:
1351 parser.feed(text)
1352 return parser.close()
1353
1354# --------------------------------------------------------------------
Armin Rigo9ed73062005-12-14 18:10:45 +00001355
1356##
1357# Generic element structure builder. This builder converts a sequence
1358# of {@link #TreeBuilder.start}, {@link #TreeBuilder.data}, and {@link
1359# #TreeBuilder.end} method calls to a well-formed element structure.
1360# <p>
1361# You can use this class to build an element structure using a custom XML
1362# parser, or a parser for some other XML-like format.
1363#
1364# @param element_factory Optional element factory. This factory
1365# is called to create new Element instances, as necessary.
1366
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001367class TreeBuilder(object):
Armin Rigo9ed73062005-12-14 18:10:45 +00001368
1369 def __init__(self, element_factory=None):
1370 self._data = [] # data collector
1371 self._elem = [] # element stack
1372 self._last = None # last element
1373 self._tail = None # true if we're after an end tag
1374 if element_factory is None:
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001375 element_factory = Element
Armin Rigo9ed73062005-12-14 18:10:45 +00001376 self._factory = element_factory
1377
1378 ##
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001379 # Flushes the builder buffers, and returns the toplevel document
Armin Rigo9ed73062005-12-14 18:10:45 +00001380 # element.
1381 #
1382 # @return An Element instance.
1383 # @defreturn Element
1384
1385 def close(self):
1386 assert len(self._elem) == 0, "missing end tags"
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001387 assert self._last is not None, "missing toplevel element"
Armin Rigo9ed73062005-12-14 18:10:45 +00001388 return self._last
1389
1390 def _flush(self):
1391 if self._data:
1392 if self._last is not None:
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001393 text = "".join(self._data)
Armin Rigo9ed73062005-12-14 18:10:45 +00001394 if self._tail:
1395 assert self._last.tail is None, "internal error (tail)"
1396 self._last.tail = text
1397 else:
1398 assert self._last.text is None, "internal error (text)"
1399 self._last.text = text
1400 self._data = []
1401
1402 ##
1403 # Adds text to the current element.
1404 #
1405 # @param data A string. This should be either an 8-bit string
1406 # containing ASCII text, or a Unicode string.
1407
1408 def data(self, data):
1409 self._data.append(data)
1410
1411 ##
1412 # Opens a new element.
1413 #
1414 # @param tag The element name.
1415 # @param attrib A dictionary containing element attributes.
1416 # @return The opened element.
1417 # @defreturn Element
1418
1419 def start(self, tag, attrs):
1420 self._flush()
1421 self._last = elem = self._factory(tag, attrs)
1422 if self._elem:
1423 self._elem[-1].append(elem)
1424 self._elem.append(elem)
1425 self._tail = 0
1426 return elem
1427
1428 ##
1429 # Closes the current element.
1430 #
1431 # @param tag The element name.
1432 # @return The closed element.
1433 # @defreturn Element
1434
1435 def end(self, tag):
1436 self._flush()
1437 self._last = self._elem.pop()
1438 assert self._last.tag == tag,\
1439 "end tag mismatch (expected %s, got %s)" % (
1440 self._last.tag, tag)
1441 self._tail = 1
1442 return self._last
1443
1444##
1445# Element structure builder for XML source data, based on the
1446# <b>expat</b> parser.
1447#
1448# @keyparam target Target object. If omitted, the builder uses an
1449# instance of the standard {@link #TreeBuilder} class.
1450# @keyparam html Predefine HTML entities. This flag is not supported
1451# by the current implementation.
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001452# @keyparam encoding Optional encoding. If given, the value overrides
1453# the encoding specified in the XML file.
Armin Rigo9ed73062005-12-14 18:10:45 +00001454# @see #ElementTree
1455# @see #TreeBuilder
1456
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001457class XMLParser(object):
Armin Rigo9ed73062005-12-14 18:10:45 +00001458
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001459 def __init__(self, html=0, target=None, encoding=None):
Armin Rigo9ed73062005-12-14 18:10:45 +00001460 try:
Fred Drakefbdeaad2006-07-29 16:56:15 +00001461 from xml.parsers import expat
Armin Rigo9ed73062005-12-14 18:10:45 +00001462 except ImportError:
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001463 try:
1464 import pyexpat as expat
1465 except ImportError:
1466 raise ImportError(
1467 "No module named expat; use SimpleXMLTreeBuilder instead"
1468 )
1469 parser = expat.ParserCreate(encoding, "}")
Armin Rigo9ed73062005-12-14 18:10:45 +00001470 if target is None:
1471 target = TreeBuilder()
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001472 # underscored names are provided for compatibility only
1473 self.parser = self._parser = parser
1474 self.target = self._target = target
1475 self._error = expat.error
Armin Rigo9ed73062005-12-14 18:10:45 +00001476 self._names = {} # name memo cache
1477 # callbacks
1478 parser.DefaultHandlerExpand = self._default
1479 parser.StartElementHandler = self._start
1480 parser.EndElementHandler = self._end
1481 parser.CharacterDataHandler = self._data
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001482 # optional callbacks
1483 parser.CommentHandler = self._comment
1484 parser.ProcessingInstructionHandler = self._pi
Armin Rigo9ed73062005-12-14 18:10:45 +00001485 # let expat do the buffering, if supported
1486 try:
1487 self._parser.buffer_text = 1
1488 except AttributeError:
1489 pass
1490 # use new-style attribute handling, if supported
1491 try:
1492 self._parser.ordered_attributes = 1
1493 self._parser.specified_attributes = 1
1494 parser.StartElementHandler = self._start_list
1495 except AttributeError:
1496 pass
Armin Rigo9ed73062005-12-14 18:10:45 +00001497 self._doctype = None
1498 self.entity = {}
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001499 try:
1500 self.version = "Expat %d.%d.%d" % expat.version_info
1501 except AttributeError:
1502 pass # unknown
1503
1504 def _raiseerror(self, value):
1505 err = ParseError(value)
1506 err.code = value.code
1507 err.position = value.lineno, value.offset
1508 raise err
Armin Rigo9ed73062005-12-14 18:10:45 +00001509
1510 def _fixtext(self, text):
1511 # convert text string to ascii, if possible
1512 try:
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001513 return text.encode("ascii")
Armin Rigo9ed73062005-12-14 18:10:45 +00001514 except UnicodeError:
1515 return text
1516
1517 def _fixname(self, key):
1518 # expand qname, and convert name string to ascii, if possible
1519 try:
1520 name = self._names[key]
1521 except KeyError:
1522 name = key
1523 if "}" in name:
1524 name = "{" + name
1525 self._names[key] = name = self._fixtext(name)
1526 return name
1527
1528 def _start(self, tag, attrib_in):
1529 fixname = self._fixname
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001530 fixtext = self._fixtext
Armin Rigo9ed73062005-12-14 18:10:45 +00001531 tag = fixname(tag)
1532 attrib = {}
1533 for key, value in attrib_in.items():
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001534 attrib[fixname(key)] = fixtext(value)
1535 return self.target.start(tag, attrib)
Armin Rigo9ed73062005-12-14 18:10:45 +00001536
1537 def _start_list(self, tag, attrib_in):
1538 fixname = self._fixname
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001539 fixtext = self._fixtext
Armin Rigo9ed73062005-12-14 18:10:45 +00001540 tag = fixname(tag)
1541 attrib = {}
1542 if attrib_in:
1543 for i in range(0, len(attrib_in), 2):
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001544 attrib[fixname(attrib_in[i])] = fixtext(attrib_in[i+1])
1545 return self.target.start(tag, attrib)
Armin Rigo9ed73062005-12-14 18:10:45 +00001546
1547 def _data(self, text):
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001548 return self.target.data(self._fixtext(text))
Armin Rigo9ed73062005-12-14 18:10:45 +00001549
1550 def _end(self, tag):
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001551 return self.target.end(self._fixname(tag))
1552
1553 def _comment(self, data):
1554 try:
1555 comment = self.target.comment
1556 except AttributeError:
1557 pass
1558 else:
1559 return comment(self._fixtext(data))
1560
1561 def _pi(self, target, data):
1562 try:
1563 pi = self.target.pi
1564 except AttributeError:
1565 pass
1566 else:
1567 return pi(self._fixtext(target), self._fixtext(data))
Armin Rigo9ed73062005-12-14 18:10:45 +00001568
1569 def _default(self, text):
1570 prefix = text[:1]
1571 if prefix == "&":
1572 # deal with undefined entities
1573 try:
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001574 self.target.data(self.entity[text[1:-1]])
Armin Rigo9ed73062005-12-14 18:10:45 +00001575 except KeyError:
Fred Drakefbdeaad2006-07-29 16:56:15 +00001576 from xml.parsers import expat
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001577 err = expat.error(
Armin Rigo9ed73062005-12-14 18:10:45 +00001578 "undefined entity %s: line %d, column %d" %
1579 (text, self._parser.ErrorLineNumber,
1580 self._parser.ErrorColumnNumber)
1581 )
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001582 err.code = 11 # XML_ERROR_UNDEFINED_ENTITY
1583 err.lineno = self._parser.ErrorLineNumber
1584 err.offset = self._parser.ErrorColumnNumber
1585 raise err
Armin Rigo9ed73062005-12-14 18:10:45 +00001586 elif prefix == "<" and text[:9] == "<!DOCTYPE":
1587 self._doctype = [] # inside a doctype declaration
1588 elif self._doctype is not None:
1589 # parse doctype contents
1590 if prefix == ">":
1591 self._doctype = None
1592 return
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001593 text = text.strip()
Armin Rigo9ed73062005-12-14 18:10:45 +00001594 if not text:
1595 return
1596 self._doctype.append(text)
1597 n = len(self._doctype)
1598 if n > 2:
1599 type = self._doctype[1]
1600 if type == "PUBLIC" and n == 4:
1601 name, type, pubid, system = self._doctype
1602 elif type == "SYSTEM" and n == 3:
1603 name, type, system = self._doctype
1604 pubid = None
1605 else:
1606 return
1607 if pubid:
1608 pubid = pubid[1:-1]
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001609 if hasattr(self.target, "doctype"):
1610 self.target.doctype(name, pubid, system[1:-1])
1611 elif self.doctype is not self._XMLParser__doctype:
1612 # warn about deprecated call
1613 self._XMLParser__doctype(name, pubid, system[1:-1])
1614 self.doctype(name, pubid, system[1:-1])
Armin Rigo9ed73062005-12-14 18:10:45 +00001615 self._doctype = None
1616
1617 ##
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001618 # (Deprecated) Handles a doctype declaration.
Armin Rigo9ed73062005-12-14 18:10:45 +00001619 #
1620 # @param name Doctype name.
1621 # @param pubid Public identifier.
1622 # @param system System identifier.
1623
1624 def doctype(self, name, pubid, system):
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001625 """This method of XMLParser is deprecated."""
1626 warnings.warn(
1627 "This method of XMLParser is deprecated. Define doctype() "
1628 "method on the TreeBuilder target.",
1629 DeprecationWarning,
1630 )
1631
1632 # sentinel, if doctype is redefined in a subclass
1633 __doctype = doctype
Armin Rigo9ed73062005-12-14 18:10:45 +00001634
1635 ##
1636 # Feeds data to the parser.
1637 #
1638 # @param data Encoded data.
1639
1640 def feed(self, data):
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001641 try:
1642 self._parser.Parse(data, 0)
1643 except self._error, v:
1644 self._raiseerror(v)
Armin Rigo9ed73062005-12-14 18:10:45 +00001645
1646 ##
1647 # Finishes feeding data to the parser.
1648 #
1649 # @return An element structure.
1650 # @defreturn Element
1651
1652 def close(self):
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001653 try:
1654 self._parser.Parse("", 1) # end of data
1655 except self._error, v:
1656 self._raiseerror(v)
1657 tree = self.target.close()
1658 del self.target, self._parser # get rid of circular references
Armin Rigo9ed73062005-12-14 18:10:45 +00001659 return tree
Fredrik Lundhbf84e542006-07-06 12:29:24 +00001660
1661# compatibility
Florent Xicluna3e8c1892010-03-11 14:36:19 +00001662XMLTreeBuilder = XMLParser
1663
1664# workaround circular import.
1665try:
1666 from ElementC14N import _serialize_c14n
1667 _serialize["c14n"] = _serialize_c14n
1668except ImportError:
1669 pass