Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1 | """Lightweight XML support for Python. |
| 2 | |
| 3 | XML is an inherently hierarchical data format, and the most natural way to |
| 4 | represent it is with a tree. This module has two classes for this purpose: |
| 5 | |
| 6 | 1. ElementTree represents the whole XML document as a tree and |
| 7 | |
| 8 | 2. Element represents a single node in this tree. |
| 9 | |
| 10 | Interactions with the whole document (reading and writing to/from files) are |
| 11 | usually done on the ElementTree level. Interactions with a single XML element |
| 12 | and its sub-elements are done on the Element level. |
| 13 | |
| 14 | Element is a flexible container object designed to store hierarchical data |
| 15 | structures in memory. It can be described as a cross between a list and a |
| 16 | dictionary. Each Element has a number of properties associated with it: |
| 17 | |
| 18 | 'tag' - a string containing the element's name. |
| 19 | |
| 20 | 'attributes' - a Python dictionary storing the element's attributes. |
| 21 | |
| 22 | 'text' - a string containing the element's text content. |
| 23 | |
| 24 | 'tail' - an optional string containing text after the element's end tag. |
| 25 | |
| 26 | And a number of child elements stored in a Python sequence. |
| 27 | |
| 28 | To create an element instance, use the Element constructor, |
| 29 | or the SubElement factory function. |
| 30 | |
| 31 | You can also use the ElementTree class to wrap an element structure |
| 32 | and convert it to and from XML. |
| 33 | |
| 34 | """ |
| 35 | |
Eli Bendersky | bf05df2 | 2013-04-20 05:44:01 -0700 | [diff] [blame] | 36 | #--------------------------------------------------------------------- |
| 37 | # Licensed to PSF under a Contributor Agreement. |
| 38 | # See http://www.python.org/psf/license for licensing details. |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 39 | # |
| 40 | # ElementTree |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 41 | # Copyright (c) 1999-2008 by Fredrik Lundh. All rights reserved. |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 42 | # |
| 43 | # fredrik@pythonware.com |
| 44 | # http://www.pythonware.com |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 45 | # -------------------------------------------------------------------- |
| 46 | # The ElementTree toolkit is |
| 47 | # |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 48 | # Copyright (c) 1999-2008 by Fredrik Lundh |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 49 | # |
| 50 | # By obtaining, using, and/or copying this software and/or its |
| 51 | # associated documentation, you agree that you have read, understood, |
| 52 | # and will comply with the following terms and conditions: |
| 53 | # |
| 54 | # Permission to use, copy, modify, and distribute this software and |
| 55 | # its associated documentation for any purpose and without fee is |
| 56 | # hereby granted, provided that the above copyright notice appears in |
| 57 | # all copies, and that both that copyright notice and this permission |
| 58 | # notice appear in supporting documentation, and that the name of |
| 59 | # Secret Labs AB or the author not be used in advertising or publicity |
| 60 | # pertaining to distribution of the software without specific, written |
| 61 | # prior permission. |
| 62 | # |
| 63 | # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD |
| 64 | # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- |
| 65 | # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR |
| 66 | # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY |
| 67 | # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, |
| 68 | # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS |
| 69 | # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE |
| 70 | # OF THIS SOFTWARE. |
| 71 | # -------------------------------------------------------------------- |
| 72 | |
| 73 | __all__ = [ |
| 74 | # public symbols |
| 75 | "Comment", |
| 76 | "dump", |
| 77 | "Element", "ElementTree", |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 78 | "fromstring", "fromstringlist", |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 79 | "iselement", "iterparse", |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 80 | "parse", "ParseError", |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 81 | "PI", "ProcessingInstruction", |
| 82 | "QName", |
| 83 | "SubElement", |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 84 | "tostring", "tostringlist", |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 85 | "TreeBuilder", |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 86 | "VERSION", |
Florent Xicluna | a72a98f | 2012-02-13 11:03:30 +0100 | [diff] [blame] | 87 | "XML", "XMLID", |
Eli Bendersky | c4e98a6 | 2013-05-19 09:24:43 -0700 | [diff] [blame] | 88 | "XMLParser", |
Florent Xicluna | a72a98f | 2012-02-13 11:03:30 +0100 | [diff] [blame] | 89 | "register_namespace", |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 90 | ] |
| 91 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 92 | VERSION = "1.3.0" |
| 93 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 94 | import sys |
| 95 | import re |
| 96 | import warnings |
Eli Bendersky | 00f402b | 2012-07-15 06:02:22 +0300 | [diff] [blame] | 97 | import io |
| 98 | import contextlib |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 99 | |
Eli Bendersky | 27cbb19 | 2012-06-15 09:03:19 +0300 | [diff] [blame] | 100 | from . import ElementPath |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 101 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 102 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 103 | class ParseError(SyntaxError): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 104 | """An error when parsing an XML document. |
| 105 | |
| 106 | In addition to its exception value, a ParseError contains |
| 107 | two extra attributes: |
| 108 | 'code' - the specific exception code |
| 109 | 'position' - the line and column of the error |
| 110 | |
| 111 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 112 | pass |
| 113 | |
| 114 | # -------------------------------------------------------------------- |
| 115 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 116 | |
| 117 | def iselement(element): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 118 | """Return True if *element* appears to be an Element.""" |
Florent Xicluna | a72a98f | 2012-02-13 11:03:30 +0100 | [diff] [blame] | 119 | return hasattr(element, 'tag') |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 120 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 121 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 122 | class Element: |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 123 | """An XML element. |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 124 | |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 125 | This class is the reference implementation of the Element interface. |
| 126 | |
| 127 | An element's length is its number of subelements. That means if you |
Serhiy Storchaka | 56a6d85 | 2014-12-01 18:28:43 +0200 | [diff] [blame] | 128 | want to check if an element is truly empty, you should check BOTH |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 129 | its length AND its text attribute. |
| 130 | |
| 131 | The element tag, attribute names, and attribute values can be either |
| 132 | bytes or strings. |
| 133 | |
| 134 | *tag* is the element name. *attrib* is an optional dictionary containing |
| 135 | element attributes. *extra* are additional element attributes given as |
| 136 | keyword arguments. |
| 137 | |
| 138 | Example form: |
| 139 | <tag attrib>text<child/>...</tag>tail |
| 140 | |
| 141 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 142 | |
| 143 | tag = None |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 144 | """The element's name.""" |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 145 | |
| 146 | attrib = None |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 147 | """Dictionary of the element's attributes.""" |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 148 | |
| 149 | text = None |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 150 | """ |
| 151 | Text before first subelement. This is either a string or the value None. |
| 152 | Note that if there is no text, this attribute may be either |
| 153 | None or the empty string, depending on the parser. |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 154 | |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 155 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 156 | |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 157 | tail = None |
| 158 | """ |
| 159 | Text after this element's end tag, but before the next sibling element's |
| 160 | start tag. This is either a string or the value None. Note that if there |
| 161 | was no text, this attribute may be either None or an empty string, |
| 162 | depending on the parser. |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 163 | |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 164 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 165 | |
| 166 | def __init__(self, tag, attrib={}, **extra): |
Eli Bendersky | 737b173 | 2012-05-29 06:02:56 +0300 | [diff] [blame] | 167 | if not isinstance(attrib, dict): |
| 168 | raise TypeError("attrib must be dict, not %s" % ( |
| 169 | attrib.__class__.__name__,)) |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 170 | attrib = attrib.copy() |
| 171 | attrib.update(extra) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 172 | self.tag = tag |
| 173 | self.attrib = attrib |
| 174 | self._children = [] |
| 175 | |
| 176 | def __repr__(self): |
Serhiy Storchaka | 465e60e | 2014-07-25 23:36:00 +0300 | [diff] [blame] | 177 | return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self)) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 178 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 179 | def makeelement(self, tag, attrib): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 180 | """Create a new element with the same type. |
| 181 | |
| 182 | *tag* is a string containing the element name. |
| 183 | *attrib* is a dictionary containing the element attributes. |
| 184 | |
| 185 | Do not call this method, use the SubElement factory function instead. |
| 186 | |
| 187 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 188 | return self.__class__(tag, attrib) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 189 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 190 | def copy(self): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 191 | """Return copy of current element. |
| 192 | |
| 193 | This creates a shallow copy. Subelements will be shared with the |
| 194 | original tree. |
| 195 | |
| 196 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 197 | elem = self.makeelement(self.tag, self.attrib) |
| 198 | elem.text = self.text |
| 199 | elem.tail = self.tail |
| 200 | elem[:] = self |
| 201 | return elem |
| 202 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 203 | def __len__(self): |
| 204 | return len(self._children) |
| 205 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 206 | def __bool__(self): |
| 207 | warnings.warn( |
| 208 | "The behavior of this method will change in future versions. " |
| 209 | "Use specific 'len(elem)' or 'elem is not None' test instead.", |
| 210 | FutureWarning, stacklevel=2 |
| 211 | ) |
| 212 | return len(self._children) != 0 # emulate old behaviour, for now |
| 213 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 214 | def __getitem__(self, index): |
| 215 | return self._children[index] |
| 216 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 217 | def __setitem__(self, index, element): |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 218 | # if isinstance(index, slice): |
| 219 | # for elt in element: |
| 220 | # assert iselement(elt) |
| 221 | # else: |
| 222 | # assert iselement(element) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 223 | self._children[index] = element |
| 224 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 225 | def __delitem__(self, index): |
| 226 | del self._children[index] |
| 227 | |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 228 | def append(self, subelement): |
| 229 | """Add *subelement* to the end of this element. |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 230 | |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 231 | The new element will appear in document order after the last existing |
| 232 | subelement (or directly after the text, if it's the first subelement), |
| 233 | but before the end tag for this element. |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 234 | |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 235 | """ |
| 236 | self._assert_is_element(subelement) |
| 237 | self._children.append(subelement) |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 238 | |
| 239 | def extend(self, elements): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 240 | """Append subelements from a sequence. |
| 241 | |
| 242 | *elements* is a sequence with zero or more elements. |
| 243 | |
| 244 | """ |
Eli Bendersky | 396e8fc | 2012-03-23 14:24:20 +0200 | [diff] [blame] | 245 | for element in elements: |
| 246 | self._assert_is_element(element) |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 247 | self._children.extend(elements) |
| 248 | |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 249 | def insert(self, index, subelement): |
| 250 | """Insert *subelement* at position *index*.""" |
| 251 | self._assert_is_element(subelement) |
| 252 | self._children.insert(index, subelement) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 253 | |
Eli Bendersky | 396e8fc | 2012-03-23 14:24:20 +0200 | [diff] [blame] | 254 | def _assert_is_element(self, e): |
Antoine Pitrou | ee32931 | 2012-10-04 19:53:29 +0200 | [diff] [blame] | 255 | # Need to refer to the actual Python implementation, not the |
| 256 | # shadowing C implementation. |
Eli Bendersky | 46955b2 | 2013-05-19 09:20:50 -0700 | [diff] [blame] | 257 | if not isinstance(e, _Element_Py): |
Eli Bendersky | 396e8fc | 2012-03-23 14:24:20 +0200 | [diff] [blame] | 258 | raise TypeError('expected an Element, not %s' % type(e).__name__) |
| 259 | |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 260 | def remove(self, subelement): |
| 261 | """Remove matching subelement. |
| 262 | |
| 263 | Unlike the find methods, this method compares elements based on |
| 264 | identity, NOT ON tag value or contents. To remove subelements by |
| 265 | other means, the easiest way is to use a list comprehension to |
| 266 | select what elements to keep, and then use slice assignment to update |
| 267 | the parent element. |
| 268 | |
| 269 | ValueError is raised if a matching element could not be found. |
| 270 | |
| 271 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 272 | # assert iselement(element) |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 273 | self._children.remove(subelement) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 274 | |
| 275 | def getchildren(self): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 276 | """(Deprecated) Return all subelements. |
| 277 | |
| 278 | Elements are returned in document order. |
| 279 | |
| 280 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 281 | warnings.warn( |
| 282 | "This method will be removed in future versions. " |
| 283 | "Use 'list(elem)' or iteration over elem instead.", |
| 284 | DeprecationWarning, stacklevel=2 |
| 285 | ) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 286 | return self._children |
| 287 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 288 | def find(self, path, namespaces=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 289 | """Find first matching element by tag name or path. |
| 290 | |
| 291 | *path* is a string having either an element tag or an XPath, |
| 292 | *namespaces* is an optional mapping from namespace prefix to full name. |
| 293 | |
| 294 | Return the first matching element, or None if no element was found. |
| 295 | |
| 296 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 297 | return ElementPath.find(self, path, namespaces) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 298 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 299 | def findtext(self, path, default=None, namespaces=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 300 | """Find text for first matching element by tag name or path. |
| 301 | |
| 302 | *path* is a string having either an element tag or an XPath, |
| 303 | *default* is the value to return if the element was not found, |
| 304 | *namespaces* is an optional mapping from namespace prefix to full name. |
| 305 | |
| 306 | Return text content of first matching element, or default value if |
| 307 | none was found. Note that if an element is found having no text |
| 308 | content, the empty string is returned. |
| 309 | |
| 310 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 311 | return ElementPath.findtext(self, path, default, namespaces) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 312 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 313 | def findall(self, path, namespaces=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 314 | """Find all matching subelements by tag name or path. |
| 315 | |
| 316 | *path* is a string having either an element tag or an XPath, |
| 317 | *namespaces* is an optional mapping from namespace prefix to full name. |
| 318 | |
| 319 | Returns list containing all matching elements in document order. |
| 320 | |
| 321 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 322 | return ElementPath.findall(self, path, namespaces) |
| 323 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 324 | def iterfind(self, path, namespaces=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 325 | """Find all matching subelements by tag name or path. |
| 326 | |
| 327 | *path* is a string having either an element tag or an XPath, |
| 328 | *namespaces* is an optional mapping from namespace prefix to full name. |
| 329 | |
| 330 | Return an iterable yielding all matching elements in document order. |
| 331 | |
| 332 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 333 | return ElementPath.iterfind(self, path, namespaces) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 334 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 335 | def clear(self): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 336 | """Reset element. |
| 337 | |
| 338 | This function removes all subelements, clears all attributes, and sets |
| 339 | the text and tail attributes to None. |
| 340 | |
| 341 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 342 | self.attrib.clear() |
| 343 | self._children = [] |
| 344 | self.text = self.tail = None |
| 345 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 346 | def get(self, key, default=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 347 | """Get element attribute. |
| 348 | |
| 349 | Equivalent to attrib.get, but some implementations may handle this a |
| 350 | bit more efficiently. *key* is what attribute to look for, and |
| 351 | *default* is what to return if the attribute was not found. |
| 352 | |
| 353 | Returns a string containing the attribute value, or the default if |
| 354 | attribute was not found. |
| 355 | |
| 356 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 357 | return self.attrib.get(key, default) |
| 358 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 359 | def set(self, key, value): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 360 | """Set element attribute. |
| 361 | |
| 362 | Equivalent to attrib[key] = value, but some implementations may handle |
| 363 | this a bit more efficiently. *key* is what attribute to set, and |
| 364 | *value* is the attribute value to set it to. |
| 365 | |
| 366 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 367 | self.attrib[key] = value |
| 368 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 369 | def keys(self): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 370 | """Get list of attribute names. |
| 371 | |
| 372 | Names are returned in an arbitrary order, just like an ordinary |
| 373 | Python dict. Equivalent to attrib.keys() |
| 374 | |
| 375 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 376 | return self.attrib.keys() |
| 377 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 378 | def items(self): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 379 | """Get element attributes as a sequence. |
| 380 | |
| 381 | The attributes are returned in arbitrary order. Equivalent to |
| 382 | attrib.items(). |
| 383 | |
| 384 | Return a list of (name, value) tuples. |
| 385 | |
| 386 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 387 | return self.attrib.items() |
| 388 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 389 | def iter(self, tag=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 390 | """Create tree iterator. |
| 391 | |
| 392 | The iterator loops over the element and all subelements in document |
| 393 | order, returning all elements with a matching tag. |
| 394 | |
| 395 | If the tree structure is modified during iteration, new or removed |
| 396 | elements may or may not be included. To get a stable set, use the |
| 397 | list() function on the iterator, and loop over the resulting list. |
| 398 | |
| 399 | *tag* is what tags to look for (default is to return all elements) |
| 400 | |
| 401 | Return an iterator containing all the matching elements. |
| 402 | |
| 403 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 404 | if tag == "*": |
| 405 | tag = None |
| 406 | if tag is None or self.tag == tag: |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 407 | yield self |
| 408 | for e in self._children: |
Philip Jenvey | fd0d3e5 | 2012-10-01 15:34:31 -0700 | [diff] [blame] | 409 | yield from e.iter(tag) |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 410 | |
| 411 | # compatibility |
| 412 | def getiterator(self, tag=None): |
| 413 | # Change for a DeprecationWarning in 1.4 |
| 414 | warnings.warn( |
| 415 | "This method will be removed in future versions. " |
| 416 | "Use 'elem.iter()' or 'list(elem.iter())' instead.", |
| 417 | PendingDeprecationWarning, stacklevel=2 |
| 418 | ) |
| 419 | return list(self.iter(tag)) |
| 420 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 421 | def itertext(self): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 422 | """Create text iterator. |
| 423 | |
| 424 | The iterator loops over the element and all subelements in document |
| 425 | order, returning all inner text. |
| 426 | |
| 427 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 428 | tag = self.tag |
| 429 | if not isinstance(tag, str) and tag is not None: |
| 430 | return |
| 431 | if self.text: |
| 432 | yield self.text |
| 433 | for e in self: |
Philip Jenvey | fd0d3e5 | 2012-10-01 15:34:31 -0700 | [diff] [blame] | 434 | yield from e.itertext() |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 435 | if e.tail: |
| 436 | yield e.tail |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 437 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 438 | |
| 439 | def SubElement(parent, tag, attrib={}, **extra): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 440 | """Subelement factory which creates an element instance, and appends it |
| 441 | to an existing parent. |
| 442 | |
| 443 | The element tag, attribute names, and attribute values can be either |
| 444 | bytes or Unicode strings. |
| 445 | |
| 446 | *parent* is the parent element, *tag* is the subelements name, *attrib* is |
| 447 | an optional directory containing element attributes, *extra* are |
| 448 | additional attributes given as keyword arguments. |
| 449 | |
| 450 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 451 | attrib = attrib.copy() |
| 452 | attrib.update(extra) |
| 453 | element = parent.makeelement(tag, attrib) |
| 454 | parent.append(element) |
| 455 | return element |
| 456 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 457 | |
| 458 | def Comment(text=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 459 | """Comment element factory. |
| 460 | |
| 461 | This function creates a special element which the standard serializer |
| 462 | serializes as an XML comment. |
| 463 | |
| 464 | *text* is a string containing the comment string. |
| 465 | |
| 466 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 467 | element = Element(Comment) |
| 468 | element.text = text |
| 469 | return element |
| 470 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 471 | |
| 472 | def ProcessingInstruction(target, text=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 473 | """Processing Instruction element factory. |
| 474 | |
| 475 | This function creates a special element which the standard serializer |
| 476 | serializes as an XML comment. |
| 477 | |
| 478 | *target* is a string containing the processing instruction, *text* is a |
| 479 | string containing the processing instruction contents, if any. |
| 480 | |
| 481 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 482 | element = Element(ProcessingInstruction) |
| 483 | element.text = target |
| 484 | if text: |
| 485 | element.text = element.text + " " + text |
| 486 | return element |
| 487 | |
| 488 | PI = ProcessingInstruction |
| 489 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 490 | |
| 491 | class QName: |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 492 | """Qualified name wrapper. |
| 493 | |
| 494 | This class can be used to wrap a QName attribute value in order to get |
| 495 | proper namespace handing on output. |
| 496 | |
| 497 | *text_or_uri* is a string containing the QName value either in the form |
| 498 | {uri}local, or if the tag argument is given, the URI part of a QName. |
| 499 | |
| 500 | *tag* is an optional argument which if given, will make the first |
| 501 | argument (text_or_uri) be interpreted as a URI, and this argument (tag) |
| 502 | be interpreted as a local name. |
| 503 | |
| 504 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 505 | def __init__(self, text_or_uri, tag=None): |
| 506 | if tag: |
| 507 | text_or_uri = "{%s}%s" % (text_or_uri, tag) |
| 508 | self.text = text_or_uri |
| 509 | def __str__(self): |
| 510 | return self.text |
Georg Brandl | b56c0e2 | 2010-12-09 18:10:27 +0000 | [diff] [blame] | 511 | def __repr__(self): |
Serhiy Storchaka | 465e60e | 2014-07-25 23:36:00 +0300 | [diff] [blame] | 512 | return '<%s %r>' % (self.__class__.__name__, self.text) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 513 | def __hash__(self): |
| 514 | return hash(self.text) |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 515 | def __le__(self, other): |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 516 | if isinstance(other, QName): |
Mark Dickinson | a56c467 | 2009-01-27 18:17:45 +0000 | [diff] [blame] | 517 | return self.text <= other.text |
| 518 | return self.text <= other |
| 519 | def __lt__(self, other): |
| 520 | if isinstance(other, QName): |
| 521 | return self.text < other.text |
| 522 | return self.text < other |
| 523 | def __ge__(self, other): |
| 524 | if isinstance(other, QName): |
| 525 | return self.text >= other.text |
| 526 | return self.text >= other |
| 527 | def __gt__(self, other): |
| 528 | if isinstance(other, QName): |
| 529 | return self.text > other.text |
| 530 | return self.text > other |
| 531 | def __eq__(self, other): |
| 532 | if isinstance(other, QName): |
| 533 | return self.text == other.text |
| 534 | return self.text == other |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 535 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 536 | # -------------------------------------------------------------------- |
| 537 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 538 | |
| 539 | class ElementTree: |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 540 | """An XML element hierarchy. |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 541 | |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 542 | This class also provides support for serialization to and from |
| 543 | standard XML. |
| 544 | |
| 545 | *element* is an optional root element node, |
| 546 | *file* is an optional file handle or file name of an XML file whose |
| 547 | contents will be used to initialize the tree with. |
| 548 | |
| 549 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 550 | def __init__(self, element=None, file=None): |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 551 | # assert element is None or iselement(element) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 552 | self._root = element # first node |
| 553 | if file: |
| 554 | self.parse(file) |
| 555 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 556 | def getroot(self): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 557 | """Return root element of this tree.""" |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 558 | return self._root |
| 559 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 560 | def _setroot(self, element): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 561 | """Replace root element of this tree. |
| 562 | |
| 563 | This will discard the current contents of the tree and replace it |
| 564 | with the given element. Use with care! |
| 565 | |
| 566 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 567 | # assert iselement(element) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 568 | self._root = element |
| 569 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 570 | def parse(self, source, parser=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 571 | """Load external XML document into element tree. |
| 572 | |
| 573 | *source* is a file name or file object, *parser* is an optional parser |
| 574 | instance that defaults to XMLParser. |
| 575 | |
| 576 | ParseError is raised if the parser fails to parse the document. |
| 577 | |
| 578 | Returns the root element of the given source document. |
| 579 | |
| 580 | """ |
Antoine Pitrou | e033e06 | 2010-10-29 10:38:18 +0000 | [diff] [blame] | 581 | close_source = False |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 582 | if not hasattr(source, "read"): |
| 583 | source = open(source, "rb") |
Antoine Pitrou | e033e06 | 2010-10-29 10:38:18 +0000 | [diff] [blame] | 584 | close_source = True |
| 585 | try: |
Eli Bendersky | a369923 | 2013-05-19 18:47:23 -0700 | [diff] [blame] | 586 | if parser is None: |
| 587 | # If no parser was specified, create a default XMLParser |
| 588 | parser = XMLParser() |
| 589 | if hasattr(parser, '_parse_whole'): |
| 590 | # The default XMLParser, when it comes from an accelerator, |
| 591 | # can define an internal _parse_whole API for efficiency. |
| 592 | # It can be used to parse the whole source without feeding |
| 593 | # it with chunks. |
| 594 | self._root = parser._parse_whole(source) |
| 595 | return self._root |
| 596 | while True: |
Antoine Pitrou | e033e06 | 2010-10-29 10:38:18 +0000 | [diff] [blame] | 597 | data = source.read(65536) |
| 598 | if not data: |
| 599 | break |
| 600 | parser.feed(data) |
| 601 | self._root = parser.close() |
| 602 | return self._root |
| 603 | finally: |
| 604 | if close_source: |
| 605 | source.close() |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 606 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 607 | def iter(self, tag=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 608 | """Create and return tree iterator for the root element. |
| 609 | |
| 610 | The iterator loops over all elements in this tree, in document order. |
| 611 | |
| 612 | *tag* is a string with the tag name to iterate over |
| 613 | (default is to return all elements). |
| 614 | |
| 615 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 616 | # assert self._root is not None |
| 617 | return self._root.iter(tag) |
| 618 | |
| 619 | # compatibility |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 620 | def getiterator(self, tag=None): |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 621 | # Change for a DeprecationWarning in 1.4 |
| 622 | warnings.warn( |
| 623 | "This method will be removed in future versions. " |
| 624 | "Use 'tree.iter()' or 'list(tree.iter())' instead.", |
| 625 | PendingDeprecationWarning, stacklevel=2 |
| 626 | ) |
| 627 | return list(self.iter(tag)) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 628 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 629 | def find(self, path, namespaces=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 630 | """Find first matching element by tag name or path. |
| 631 | |
| 632 | Same as getroot().find(path), which is Element.find() |
| 633 | |
| 634 | *path* is a string having either an element tag or an XPath, |
| 635 | *namespaces* is an optional mapping from namespace prefix to full name. |
| 636 | |
| 637 | Return the first matching element, or None if no element was found. |
| 638 | |
| 639 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 640 | # assert self._root is not None |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 641 | if path[:1] == "/": |
| 642 | path = "." + path |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 643 | warnings.warn( |
| 644 | "This search is broken in 1.3 and earlier, and will be " |
| 645 | "fixed in a future version. If you rely on the current " |
| 646 | "behaviour, change it to %r" % path, |
| 647 | FutureWarning, stacklevel=2 |
| 648 | ) |
| 649 | return self._root.find(path, namespaces) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 650 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 651 | def findtext(self, path, default=None, namespaces=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 652 | """Find first matching element by tag name or path. |
| 653 | |
| 654 | Same as getroot().findtext(path), which is Element.findtext() |
| 655 | |
| 656 | *path* is a string having either an element tag or an XPath, |
| 657 | *namespaces* is an optional mapping from namespace prefix to full name. |
| 658 | |
| 659 | Return the first matching element, or None if no element was found. |
| 660 | |
| 661 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 662 | # assert self._root is not None |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 663 | if path[:1] == "/": |
| 664 | path = "." + path |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 665 | warnings.warn( |
| 666 | "This search is broken in 1.3 and earlier, and will be " |
| 667 | "fixed in a future version. If you rely on the current " |
| 668 | "behaviour, change it to %r" % path, |
| 669 | FutureWarning, stacklevel=2 |
| 670 | ) |
| 671 | return self._root.findtext(path, default, namespaces) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 672 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 673 | def findall(self, path, namespaces=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 674 | """Find all matching subelements by tag name or path. |
| 675 | |
| 676 | Same as getroot().findall(path), which is Element.findall(). |
| 677 | |
| 678 | *path* is a string having either an element tag or an XPath, |
| 679 | *namespaces* is an optional mapping from namespace prefix to full name. |
| 680 | |
| 681 | Return list containing all matching elements in document order. |
| 682 | |
| 683 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 684 | # assert self._root is not None |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 685 | if path[:1] == "/": |
| 686 | path = "." + path |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 687 | warnings.warn( |
| 688 | "This search is broken in 1.3 and earlier, and will be " |
| 689 | "fixed in a future version. If you rely on the current " |
| 690 | "behaviour, change it to %r" % path, |
| 691 | FutureWarning, stacklevel=2 |
| 692 | ) |
| 693 | return self._root.findall(path, namespaces) |
| 694 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 695 | def iterfind(self, path, namespaces=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 696 | """Find all matching subelements by tag name or path. |
| 697 | |
| 698 | Same as getroot().iterfind(path), which is element.iterfind() |
| 699 | |
| 700 | *path* is a string having either an element tag or an XPath, |
| 701 | *namespaces* is an optional mapping from namespace prefix to full name. |
| 702 | |
| 703 | Return an iterable yielding all matching elements in document order. |
| 704 | |
| 705 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 706 | # assert self._root is not None |
| 707 | if path[:1] == "/": |
| 708 | path = "." + path |
| 709 | warnings.warn( |
| 710 | "This search is broken in 1.3 and earlier, and will be " |
| 711 | "fixed in a future version. If you rely on the current " |
| 712 | "behaviour, change it to %r" % path, |
| 713 | FutureWarning, stacklevel=2 |
| 714 | ) |
| 715 | return self._root.iterfind(path, namespaces) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 716 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 717 | def write(self, file_or_filename, |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 718 | encoding=None, |
| 719 | xml_declaration=None, |
| 720 | default_namespace=None, |
Eli Bendersky | a9a2ef5 | 2013-01-13 06:04:43 -0800 | [diff] [blame] | 721 | method=None, *, |
| 722 | short_empty_elements=True): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 723 | """Write element tree to a file as XML. |
| 724 | |
| 725 | Arguments: |
| 726 | *file_or_filename* -- file name or a file object opened for writing |
| 727 | |
| 728 | *encoding* -- the output encoding (default: US-ASCII) |
| 729 | |
| 730 | *xml_declaration* -- bool indicating if an XML declaration should be |
| 731 | added to the output. If None, an XML declaration |
| 732 | is added if encoding IS NOT either of: |
| 733 | US-ASCII, UTF-8, or Unicode |
| 734 | |
| 735 | *default_namespace* -- sets the default XML namespace (for "xmlns") |
| 736 | |
| 737 | *method* -- either "xml" (default), "html, "text", or "c14n" |
| 738 | |
| 739 | *short_empty_elements* -- controls the formatting of elements |
| 740 | that contain no content. If True (default) |
| 741 | they are emitted as a single self-closed |
| 742 | tag, otherwise they are emitted as a pair |
| 743 | of start/end tags |
Eli Bendersky | e9af827 | 2013-01-13 06:27:51 -0800 | [diff] [blame] | 744 | |
| 745 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 746 | if not method: |
| 747 | method = "xml" |
| 748 | elif method not in _serialize: |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 749 | raise ValueError("unknown method %r" % method) |
Florent Xicluna | c17f172 | 2010-08-08 19:48:29 +0000 | [diff] [blame] | 750 | if not encoding: |
| 751 | if method == "c14n": |
| 752 | encoding = "utf-8" |
| 753 | else: |
| 754 | encoding = "us-ascii" |
Florent Xicluna | c17f172 | 2010-08-08 19:48:29 +0000 | [diff] [blame] | 755 | else: |
| 756 | encoding = encoding.lower() |
Eli Bendersky | 00f402b | 2012-07-15 06:02:22 +0300 | [diff] [blame] | 757 | with _get_writer(file_or_filename, encoding) as write: |
| 758 | if method == "xml" and (xml_declaration or |
| 759 | (xml_declaration is None and |
| 760 | encoding not in ("utf-8", "us-ascii", "unicode"))): |
| 761 | declared_encoding = encoding |
| 762 | if encoding == "unicode": |
| 763 | # Retrieve the default encoding for the xml declaration |
| 764 | import locale |
| 765 | declared_encoding = locale.getpreferredencoding() |
| 766 | write("<?xml version='1.0' encoding='%s'?>\n" % ( |
| 767 | declared_encoding,)) |
| 768 | if method == "text": |
| 769 | _serialize_text(write, self._root) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 770 | else: |
Eli Bendersky | 00f402b | 2012-07-15 06:02:22 +0300 | [diff] [blame] | 771 | qnames, namespaces = _namespaces(self._root, default_namespace) |
| 772 | serialize = _serialize[method] |
Eli Bendersky | a9a2ef5 | 2013-01-13 06:04:43 -0800 | [diff] [blame] | 773 | serialize(write, self._root, qnames, namespaces, |
| 774 | short_empty_elements=short_empty_elements) |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 775 | |
| 776 | def write_c14n(self, file): |
| 777 | # lxml.etree compatibility. use output method instead |
| 778 | return self.write(file, method="c14n") |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 779 | |
| 780 | # -------------------------------------------------------------------- |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 781 | # serialization support |
| 782 | |
Eli Bendersky | 00f402b | 2012-07-15 06:02:22 +0300 | [diff] [blame] | 783 | @contextlib.contextmanager |
| 784 | def _get_writer(file_or_filename, encoding): |
Ezio Melotti | b5bc353 | 2013-08-17 16:11:40 +0300 | [diff] [blame] | 785 | # returns text write method and release all resources after using |
Eli Bendersky | 00f402b | 2012-07-15 06:02:22 +0300 | [diff] [blame] | 786 | try: |
| 787 | write = file_or_filename.write |
| 788 | except AttributeError: |
| 789 | # file_or_filename is a file name |
| 790 | if encoding == "unicode": |
| 791 | file = open(file_or_filename, "w") |
| 792 | else: |
| 793 | file = open(file_or_filename, "w", encoding=encoding, |
| 794 | errors="xmlcharrefreplace") |
| 795 | with file: |
| 796 | yield file.write |
| 797 | else: |
| 798 | # file_or_filename is a file-like object |
| 799 | # encoding determines if it is a text or binary writer |
| 800 | if encoding == "unicode": |
| 801 | # use a text writer as is |
| 802 | yield write |
| 803 | else: |
| 804 | # wrap a binary writer with TextIOWrapper |
| 805 | with contextlib.ExitStack() as stack: |
| 806 | if isinstance(file_or_filename, io.BufferedIOBase): |
| 807 | file = file_or_filename |
| 808 | elif isinstance(file_or_filename, io.RawIOBase): |
| 809 | file = io.BufferedWriter(file_or_filename) |
| 810 | # Keep the original file open when the BufferedWriter is |
| 811 | # destroyed |
| 812 | stack.callback(file.detach) |
| 813 | else: |
| 814 | # This is to handle passed objects that aren't in the |
| 815 | # IOBase hierarchy, but just have a write method |
| 816 | file = io.BufferedIOBase() |
| 817 | file.writable = lambda: True |
| 818 | file.write = write |
| 819 | try: |
| 820 | # TextIOWrapper uses this methods to determine |
| 821 | # if BOM (for UTF-16, etc) should be added |
| 822 | file.seekable = file_or_filename.seekable |
| 823 | file.tell = file_or_filename.tell |
| 824 | except AttributeError: |
| 825 | pass |
| 826 | file = io.TextIOWrapper(file, |
| 827 | encoding=encoding, |
| 828 | errors="xmlcharrefreplace", |
| 829 | newline="\n") |
| 830 | # Keep the original file open when the TextIOWrapper is |
| 831 | # destroyed |
| 832 | stack.callback(file.detach) |
| 833 | yield file.write |
| 834 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 835 | def _namespaces(elem, default_namespace=None): |
| 836 | # identify namespaces used in this tree |
| 837 | |
| 838 | # maps qnames to *encoded* prefix:local names |
| 839 | qnames = {None: None} |
| 840 | |
| 841 | # maps uri:s to prefixes |
| 842 | namespaces = {} |
| 843 | if default_namespace: |
| 844 | namespaces[default_namespace] = "" |
| 845 | |
| 846 | def add_qname(qname): |
| 847 | # calculate serialized qname representation |
| 848 | try: |
| 849 | if qname[:1] == "{": |
| 850 | uri, tag = qname[1:].rsplit("}", 1) |
| 851 | prefix = namespaces.get(uri) |
| 852 | if prefix is None: |
| 853 | prefix = _namespace_map.get(uri) |
| 854 | if prefix is None: |
| 855 | prefix = "ns%d" % len(namespaces) |
| 856 | if prefix != "xml": |
| 857 | namespaces[uri] = prefix |
| 858 | if prefix: |
| 859 | qnames[qname] = "%s:%s" % (prefix, tag) |
| 860 | else: |
| 861 | qnames[qname] = tag # default element |
| 862 | else: |
| 863 | if default_namespace: |
| 864 | # FIXME: can this be handled in XML 1.0? |
| 865 | raise ValueError( |
| 866 | "cannot use non-qualified names with " |
| 867 | "default_namespace option" |
| 868 | ) |
| 869 | qnames[qname] = qname |
| 870 | except TypeError: |
| 871 | _raise_serialization_error(qname) |
| 872 | |
| 873 | # populate qname and namespaces table |
Eli Bendersky | 64d11e6 | 2012-06-15 07:42:50 +0300 | [diff] [blame] | 874 | for elem in elem.iter(): |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 875 | tag = elem.tag |
Senthil Kumaran | ec30b3d | 2010-11-09 02:36:59 +0000 | [diff] [blame] | 876 | if isinstance(tag, QName): |
| 877 | if tag.text not in qnames: |
| 878 | add_qname(tag.text) |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 879 | elif isinstance(tag, str): |
| 880 | if tag not in qnames: |
| 881 | add_qname(tag) |
| 882 | elif tag is not None and tag is not Comment and tag is not PI: |
| 883 | _raise_serialization_error(tag) |
| 884 | for key, value in elem.items(): |
| 885 | if isinstance(key, QName): |
| 886 | key = key.text |
| 887 | if key not in qnames: |
| 888 | add_qname(key) |
| 889 | if isinstance(value, QName) and value.text not in qnames: |
| 890 | add_qname(value.text) |
| 891 | text = elem.text |
| 892 | if isinstance(text, QName) and text.text not in qnames: |
| 893 | add_qname(text.text) |
| 894 | return qnames, namespaces |
| 895 | |
Eli Bendersky | a9a2ef5 | 2013-01-13 06:04:43 -0800 | [diff] [blame] | 896 | def _serialize_xml(write, elem, qnames, namespaces, |
| 897 | short_empty_elements, **kwargs): |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 898 | tag = elem.tag |
| 899 | text = elem.text |
| 900 | if tag is Comment: |
| 901 | write("<!--%s-->" % text) |
| 902 | elif tag is ProcessingInstruction: |
| 903 | write("<?%s?>" % text) |
| 904 | else: |
| 905 | tag = qnames[tag] |
| 906 | if tag is None: |
| 907 | if text: |
| 908 | write(_escape_cdata(text)) |
| 909 | for e in elem: |
Eli Bendersky | a9a2ef5 | 2013-01-13 06:04:43 -0800 | [diff] [blame] | 910 | _serialize_xml(write, e, qnames, None, |
| 911 | short_empty_elements=short_empty_elements) |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 912 | else: |
| 913 | write("<" + tag) |
| 914 | items = list(elem.items()) |
| 915 | if items or namespaces: |
| 916 | if namespaces: |
| 917 | for v, k in sorted(namespaces.items(), |
| 918 | key=lambda x: x[1]): # sort on prefix |
| 919 | if k: |
| 920 | k = ":" + k |
| 921 | write(" xmlns%s=\"%s\"" % ( |
| 922 | k, |
| 923 | _escape_attrib(v) |
| 924 | )) |
| 925 | for k, v in sorted(items): # lexical order |
| 926 | if isinstance(k, QName): |
| 927 | k = k.text |
| 928 | if isinstance(v, QName): |
| 929 | v = qnames[v.text] |
| 930 | else: |
| 931 | v = _escape_attrib(v) |
| 932 | write(" %s=\"%s\"" % (qnames[k], v)) |
Eli Bendersky | a9a2ef5 | 2013-01-13 06:04:43 -0800 | [diff] [blame] | 933 | if text or len(elem) or not short_empty_elements: |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 934 | write(">") |
| 935 | if text: |
| 936 | write(_escape_cdata(text)) |
| 937 | for e in elem: |
Eli Bendersky | a9a2ef5 | 2013-01-13 06:04:43 -0800 | [diff] [blame] | 938 | _serialize_xml(write, e, qnames, None, |
| 939 | short_empty_elements=short_empty_elements) |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 940 | write("</" + tag + ">") |
| 941 | else: |
| 942 | write(" />") |
| 943 | if elem.tail: |
| 944 | write(_escape_cdata(elem.tail)) |
| 945 | |
| 946 | HTML_EMPTY = ("area", "base", "basefont", "br", "col", "frame", "hr", |
Ezio Melotti | c90111f | 2012-09-19 08:19:12 +0300 | [diff] [blame] | 947 | "img", "input", "isindex", "link", "meta", "param") |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 948 | |
| 949 | try: |
| 950 | HTML_EMPTY = set(HTML_EMPTY) |
| 951 | except NameError: |
| 952 | pass |
| 953 | |
Eli Bendersky | a9a2ef5 | 2013-01-13 06:04:43 -0800 | [diff] [blame] | 954 | def _serialize_html(write, elem, qnames, namespaces, **kwargs): |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 955 | tag = elem.tag |
| 956 | text = elem.text |
| 957 | if tag is Comment: |
| 958 | write("<!--%s-->" % _escape_cdata(text)) |
| 959 | elif tag is ProcessingInstruction: |
| 960 | write("<?%s?>" % _escape_cdata(text)) |
| 961 | else: |
| 962 | tag = qnames[tag] |
| 963 | if tag is None: |
| 964 | if text: |
| 965 | write(_escape_cdata(text)) |
| 966 | for e in elem: |
| 967 | _serialize_html(write, e, qnames, None) |
| 968 | else: |
| 969 | write("<" + tag) |
| 970 | items = list(elem.items()) |
| 971 | if items or namespaces: |
| 972 | if namespaces: |
| 973 | for v, k in sorted(namespaces.items(), |
| 974 | key=lambda x: x[1]): # sort on prefix |
| 975 | if k: |
| 976 | k = ":" + k |
| 977 | write(" xmlns%s=\"%s\"" % ( |
| 978 | k, |
| 979 | _escape_attrib(v) |
| 980 | )) |
| 981 | for k, v in sorted(items): # lexical order |
| 982 | if isinstance(k, QName): |
| 983 | k = k.text |
| 984 | if isinstance(v, QName): |
| 985 | v = qnames[v.text] |
| 986 | else: |
| 987 | v = _escape_attrib_html(v) |
| 988 | # FIXME: handle boolean attributes |
| 989 | write(" %s=\"%s\"" % (qnames[k], v)) |
| 990 | write(">") |
Christian Heimes | 54ad7e3 | 2013-07-05 01:39:49 +0200 | [diff] [blame] | 991 | ltag = tag.lower() |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 992 | if text: |
Christian Heimes | 54ad7e3 | 2013-07-05 01:39:49 +0200 | [diff] [blame] | 993 | if ltag == "script" or ltag == "style": |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 994 | write(text) |
| 995 | else: |
| 996 | write(_escape_cdata(text)) |
| 997 | for e in elem: |
| 998 | _serialize_html(write, e, qnames, None) |
Christian Heimes | 54ad7e3 | 2013-07-05 01:39:49 +0200 | [diff] [blame] | 999 | if ltag not in HTML_EMPTY: |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1000 | write("</" + tag + ">") |
| 1001 | if elem.tail: |
| 1002 | write(_escape_cdata(elem.tail)) |
| 1003 | |
| 1004 | def _serialize_text(write, elem): |
| 1005 | for part in elem.itertext(): |
| 1006 | write(part) |
| 1007 | if elem.tail: |
| 1008 | write(elem.tail) |
| 1009 | |
| 1010 | _serialize = { |
| 1011 | "xml": _serialize_xml, |
| 1012 | "html": _serialize_html, |
| 1013 | "text": _serialize_text, |
| 1014 | # this optional method is imported at the end of the module |
| 1015 | # "c14n": _serialize_c14n, |
| 1016 | } |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1017 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1018 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1019 | def register_namespace(prefix, uri): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1020 | """Register a namespace prefix. |
| 1021 | |
| 1022 | The registry is global, and any existing mapping for either the |
| 1023 | given prefix or the namespace URI will be removed. |
| 1024 | |
| 1025 | *prefix* is the namespace prefix, *uri* is a namespace uri. Tags and |
| 1026 | attributes in this namespace will be serialized with prefix if possible. |
| 1027 | |
| 1028 | ValueError is raised if prefix is reserved or is invalid. |
| 1029 | |
| 1030 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1031 | if re.match("ns\d+$", prefix): |
| 1032 | raise ValueError("Prefix format reserved for internal use") |
Georg Brandl | 90b2067 | 2010-12-28 10:38:33 +0000 | [diff] [blame] | 1033 | for k, v in list(_namespace_map.items()): |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1034 | if k == uri or v == prefix: |
| 1035 | del _namespace_map[k] |
| 1036 | _namespace_map[uri] = prefix |
| 1037 | |
| 1038 | _namespace_map = { |
| 1039 | # "well-known" namespace prefixes |
| 1040 | "http://www.w3.org/XML/1998/namespace": "xml", |
| 1041 | "http://www.w3.org/1999/xhtml": "html", |
| 1042 | "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf", |
| 1043 | "http://schemas.xmlsoap.org/wsdl/": "wsdl", |
| 1044 | # xml schema |
| 1045 | "http://www.w3.org/2001/XMLSchema": "xs", |
| 1046 | "http://www.w3.org/2001/XMLSchema-instance": "xsi", |
| 1047 | # dublin core |
| 1048 | "http://purl.org/dc/elements/1.1/": "dc", |
| 1049 | } |
Florent Xicluna | 1639505 | 2012-02-16 23:28:35 +0100 | [diff] [blame] | 1050 | # For tests and troubleshooting |
| 1051 | register_namespace._namespace_map = _namespace_map |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1052 | |
| 1053 | def _raise_serialization_error(text): |
| 1054 | raise TypeError( |
| 1055 | "cannot serialize %r (type %s)" % (text, type(text).__name__) |
| 1056 | ) |
| 1057 | |
| 1058 | def _escape_cdata(text): |
| 1059 | # escape character data |
| 1060 | try: |
| 1061 | # it's worth avoiding do-nothing calls for strings that are |
| 1062 | # shorter than 500 character, or so. assume that's, by far, |
| 1063 | # the most common case in most applications. |
| 1064 | if "&" in text: |
| 1065 | text = text.replace("&", "&") |
| 1066 | if "<" in text: |
| 1067 | text = text.replace("<", "<") |
| 1068 | if ">" in text: |
| 1069 | text = text.replace(">", ">") |
| 1070 | return text |
| 1071 | except (TypeError, AttributeError): |
| 1072 | _raise_serialization_error(text) |
| 1073 | |
| 1074 | def _escape_attrib(text): |
| 1075 | # escape attribute value |
| 1076 | try: |
| 1077 | if "&" in text: |
| 1078 | text = text.replace("&", "&") |
| 1079 | if "<" in text: |
| 1080 | text = text.replace("<", "<") |
| 1081 | if ">" in text: |
| 1082 | text = text.replace(">", ">") |
| 1083 | if "\"" in text: |
| 1084 | text = text.replace("\"", """) |
| 1085 | if "\n" in text: |
| 1086 | text = text.replace("\n", " ") |
| 1087 | return text |
| 1088 | except (TypeError, AttributeError): |
| 1089 | _raise_serialization_error(text) |
| 1090 | |
| 1091 | def _escape_attrib_html(text): |
| 1092 | # escape attribute value |
| 1093 | try: |
| 1094 | if "&" in text: |
| 1095 | text = text.replace("&", "&") |
| 1096 | if ">" in text: |
| 1097 | text = text.replace(">", ">") |
| 1098 | if "\"" in text: |
| 1099 | text = text.replace("\"", """) |
| 1100 | return text |
| 1101 | except (TypeError, AttributeError): |
| 1102 | _raise_serialization_error(text) |
| 1103 | |
| 1104 | # -------------------------------------------------------------------- |
| 1105 | |
Eli Bendersky | a9a2ef5 | 2013-01-13 06:04:43 -0800 | [diff] [blame] | 1106 | def tostring(element, encoding=None, method=None, *, |
| 1107 | short_empty_elements=True): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1108 | """Generate string representation of XML element. |
| 1109 | |
| 1110 | All subelements are included. If encoding is "unicode", a string |
| 1111 | is returned. Otherwise a bytestring is returned. |
| 1112 | |
| 1113 | *element* is an Element instance, *encoding* is an optional output |
| 1114 | encoding defaulting to US-ASCII, *method* is an optional output which can |
| 1115 | be one of "xml" (default), "html", "text" or "c14n". |
| 1116 | |
| 1117 | Returns an (optionally) encoded string containing the XML data. |
| 1118 | |
| 1119 | """ |
Eli Bendersky | 00f402b | 2012-07-15 06:02:22 +0300 | [diff] [blame] | 1120 | stream = io.StringIO() if encoding == 'unicode' else io.BytesIO() |
Eli Bendersky | a9a2ef5 | 2013-01-13 06:04:43 -0800 | [diff] [blame] | 1121 | ElementTree(element).write(stream, encoding, method=method, |
| 1122 | short_empty_elements=short_empty_elements) |
Eli Bendersky | 00f402b | 2012-07-15 06:02:22 +0300 | [diff] [blame] | 1123 | return stream.getvalue() |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1124 | |
Eli Bendersky | 43cc5f2 | 2012-07-17 15:09:12 +0300 | [diff] [blame] | 1125 | class _ListDataStream(io.BufferedIOBase): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1126 | """An auxiliary stream accumulating into a list reference.""" |
Eli Bendersky | 43cc5f2 | 2012-07-17 15:09:12 +0300 | [diff] [blame] | 1127 | def __init__(self, lst): |
| 1128 | self.lst = lst |
Eli Bendersky | f90fc68 | 2012-07-17 15:09:56 +0300 | [diff] [blame] | 1129 | |
Eli Bendersky | 43cc5f2 | 2012-07-17 15:09:12 +0300 | [diff] [blame] | 1130 | def writable(self): |
| 1131 | return True |
| 1132 | |
| 1133 | def seekable(self): |
| 1134 | return True |
| 1135 | |
| 1136 | def write(self, b): |
| 1137 | self.lst.append(b) |
| 1138 | |
| 1139 | def tell(self): |
| 1140 | return len(self.lst) |
| 1141 | |
Eli Bendersky | a9a2ef5 | 2013-01-13 06:04:43 -0800 | [diff] [blame] | 1142 | def tostringlist(element, encoding=None, method=None, *, |
| 1143 | short_empty_elements=True): |
Eli Bendersky | 43cc5f2 | 2012-07-17 15:09:12 +0300 | [diff] [blame] | 1144 | lst = [] |
| 1145 | stream = _ListDataStream(lst) |
Eli Bendersky | a9a2ef5 | 2013-01-13 06:04:43 -0800 | [diff] [blame] | 1146 | ElementTree(element).write(stream, encoding, method=method, |
| 1147 | short_empty_elements=short_empty_elements) |
Eli Bendersky | 43cc5f2 | 2012-07-17 15:09:12 +0300 | [diff] [blame] | 1148 | return lst |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1149 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1150 | |
| 1151 | def dump(elem): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1152 | """Write element tree or element structure to sys.stdout. |
| 1153 | |
| 1154 | This function should be used for debugging only. |
| 1155 | |
| 1156 | *elem* is either an ElementTree, or a single Element. The exact output |
| 1157 | format is implementation dependent. In this version, it's written as an |
| 1158 | ordinary XML file. |
| 1159 | |
| 1160 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1161 | # debugging |
| 1162 | if not isinstance(elem, ElementTree): |
| 1163 | elem = ElementTree(elem) |
Florent Xicluna | c17f172 | 2010-08-08 19:48:29 +0000 | [diff] [blame] | 1164 | elem.write(sys.stdout, encoding="unicode") |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1165 | tail = elem.getroot().tail |
| 1166 | if not tail or tail[-1] != "\n": |
| 1167 | sys.stdout.write("\n") |
| 1168 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1169 | # -------------------------------------------------------------------- |
| 1170 | # parsing |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1171 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1172 | |
| 1173 | def parse(source, parser=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1174 | """Parse XML document into element tree. |
| 1175 | |
| 1176 | *source* is a filename or file object containing XML data, |
| 1177 | *parser* is an optional parser instance defaulting to XMLParser. |
| 1178 | |
| 1179 | Return an ElementTree instance. |
| 1180 | |
| 1181 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1182 | tree = ElementTree() |
| 1183 | tree.parse(source, parser) |
| 1184 | return tree |
| 1185 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1186 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1187 | def iterparse(source, events=None, parser=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1188 | """Incrementally parse XML document into ElementTree. |
| 1189 | |
| 1190 | This class also reports what's going on to the user based on the |
| 1191 | *events* it is initialized with. The supported events are the strings |
| 1192 | "start", "end", "start-ns" and "end-ns" (the "ns" events are used to get |
| 1193 | detailed namespace information). If *events* is omitted, only |
| 1194 | "end" events are reported. |
| 1195 | |
| 1196 | *source* is a filename or file object containing XML data, *events* is |
| 1197 | a list of events to report back, *parser* is an optional parser instance. |
| 1198 | |
| 1199 | Returns an iterator providing (event, elem) pairs. |
| 1200 | |
| 1201 | """ |
Antoine Pitrou | e033e06 | 2010-10-29 10:38:18 +0000 | [diff] [blame] | 1202 | close_source = False |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1203 | if not hasattr(source, "read"): |
| 1204 | source = open(source, "rb") |
Antoine Pitrou | e033e06 | 2010-10-29 10:38:18 +0000 | [diff] [blame] | 1205 | close_source = True |
Antoine Pitrou | e033e06 | 2010-10-29 10:38:18 +0000 | [diff] [blame] | 1206 | return _IterParseIterator(source, events, parser, close_source) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1207 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1208 | |
Eli Bendersky | b586934 | 2013-08-30 05:51:20 -0700 | [diff] [blame] | 1209 | class XMLPullParser: |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1210 | |
Eli Bendersky | b586934 | 2013-08-30 05:51:20 -0700 | [diff] [blame] | 1211 | def __init__(self, events=None, *, _parser=None): |
| 1212 | # The _parser argument is for internal use only and must not be relied |
| 1213 | # upon in user code. It will be removed in a future release. |
| 1214 | # See http://bugs.python.org/issue17741 for more details. |
| 1215 | |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1216 | # _elementtree.c expects a list, not a deque |
| 1217 | self._events_queue = [] |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1218 | self._index = 0 |
Eli Bendersky | b586934 | 2013-08-30 05:51:20 -0700 | [diff] [blame] | 1219 | self._parser = _parser or XMLParser(target=TreeBuilder()) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1220 | # wire up the parser for event reporting |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1221 | if events is None: |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1222 | events = ("end",) |
| 1223 | self._parser._setevents(self._events_queue, events) |
| 1224 | |
Eli Bendersky | b586934 | 2013-08-30 05:51:20 -0700 | [diff] [blame] | 1225 | def feed(self, data): |
Nick Coghlan | 4cc2afa | 2013-09-28 23:50:35 +1000 | [diff] [blame] | 1226 | """Feed encoded data to parser.""" |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1227 | if self._parser is None: |
Eli Bendersky | b586934 | 2013-08-30 05:51:20 -0700 | [diff] [blame] | 1228 | raise ValueError("feed() called after end of stream") |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1229 | if data: |
| 1230 | try: |
| 1231 | self._parser.feed(data) |
| 1232 | except SyntaxError as exc: |
| 1233 | self._events_queue.append(exc) |
| 1234 | |
Nick Coghlan | 4cc2afa | 2013-09-28 23:50:35 +1000 | [diff] [blame] | 1235 | def _close_and_return_root(self): |
| 1236 | # iterparse needs this to set its root attribute properly :( |
| 1237 | root = self._parser.close() |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1238 | self._parser = None |
Nick Coghlan | 4cc2afa | 2013-09-28 23:50:35 +1000 | [diff] [blame] | 1239 | return root |
| 1240 | |
| 1241 | def close(self): |
| 1242 | """Finish feeding data to parser. |
| 1243 | |
| 1244 | Unlike XMLParser, does not return the root element. Use |
| 1245 | read_events() to consume elements from XMLPullParser. |
| 1246 | """ |
| 1247 | self._close_and_return_root() |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1248 | |
Eli Bendersky | b586934 | 2013-08-30 05:51:20 -0700 | [diff] [blame] | 1249 | def read_events(self): |
R David Murray | 410d320 | 2014-01-04 23:52:50 -0500 | [diff] [blame] | 1250 | """Return an iterator over currently available (event, elem) pairs. |
Nick Coghlan | 4cc2afa | 2013-09-28 23:50:35 +1000 | [diff] [blame] | 1251 | |
| 1252 | Events are consumed from the internal event queue as they are |
| 1253 | retrieved from the iterator. |
| 1254 | """ |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1255 | events = self._events_queue |
| 1256 | while True: |
| 1257 | index = self._index |
| 1258 | try: |
| 1259 | event = events[self._index] |
| 1260 | # Avoid retaining references to past events |
| 1261 | events[self._index] = None |
| 1262 | except IndexError: |
| 1263 | break |
| 1264 | index += 1 |
| 1265 | # Compact the list in a O(1) amortized fashion |
Nick Coghlan | 4cc2afa | 2013-09-28 23:50:35 +1000 | [diff] [blame] | 1266 | # As noted above, _elementree.c needs a list, not a deque |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1267 | if index * 2 >= len(events): |
| 1268 | events[:index] = [] |
| 1269 | self._index = 0 |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1270 | else: |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1271 | self._index = index |
| 1272 | if isinstance(event, Exception): |
| 1273 | raise event |
| 1274 | else: |
| 1275 | yield event |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1276 | |
| 1277 | |
Antoine Pitrou | 0acbcb5 | 2013-08-23 23:04:30 +0200 | [diff] [blame] | 1278 | class _IterParseIterator: |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1279 | |
| 1280 | def __init__(self, source, events, parser, close_source=False): |
Eli Bendersky | b586934 | 2013-08-30 05:51:20 -0700 | [diff] [blame] | 1281 | # Use the internal, undocumented _parser argument for now; When the |
| 1282 | # parser argument of iterparse is removed, this can be killed. |
| 1283 | self._parser = XMLPullParser(events=events, _parser=parser) |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1284 | self._file = source |
| 1285 | self._close_file = close_source |
Nick Coghlan | 4cc2afa | 2013-09-28 23:50:35 +1000 | [diff] [blame] | 1286 | self.root = self._root = None |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1287 | |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 1288 | def __next__(self): |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1289 | while 1: |
Eli Bendersky | b586934 | 2013-08-30 05:51:20 -0700 | [diff] [blame] | 1290 | for event in self._parser.read_events(): |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1291 | return event |
Antoine Pitrou | 0acbcb5 | 2013-08-23 23:04:30 +0200 | [diff] [blame] | 1292 | if self._parser._parser is None: |
Nick Coghlan | 4cc2afa | 2013-09-28 23:50:35 +1000 | [diff] [blame] | 1293 | self.root = self._root |
Florent Xicluna | 91d5193 | 2011-11-01 23:31:09 +0100 | [diff] [blame] | 1294 | if self._close_file: |
| 1295 | self._file.close() |
| 1296 | raise StopIteration |
| 1297 | # load event buffer |
Eli Bendersky | b586934 | 2013-08-30 05:51:20 -0700 | [diff] [blame] | 1298 | data = self._file.read(16 * 1024) |
Florent Xicluna | 91d5193 | 2011-11-01 23:31:09 +0100 | [diff] [blame] | 1299 | if data: |
Eli Bendersky | b586934 | 2013-08-30 05:51:20 -0700 | [diff] [blame] | 1300 | self._parser.feed(data) |
Florent Xicluna | 91d5193 | 2011-11-01 23:31:09 +0100 | [diff] [blame] | 1301 | else: |
Nick Coghlan | 4cc2afa | 2013-09-28 23:50:35 +1000 | [diff] [blame] | 1302 | self._root = self._parser._close_and_return_root() |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1303 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1304 | def __iter__(self): |
| 1305 | return self |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1306 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1307 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1308 | def XML(text, parser=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1309 | """Parse XML document from string constant. |
| 1310 | |
| 1311 | This function can be used to embed "XML Literals" in Python code. |
| 1312 | |
| 1313 | *text* is a string containing XML data, *parser* is an |
| 1314 | optional parser instance, defaulting to the standard XMLParser. |
| 1315 | |
| 1316 | Returns an Element instance. |
| 1317 | |
| 1318 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1319 | if not parser: |
| 1320 | parser = XMLParser(target=TreeBuilder()) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1321 | parser.feed(text) |
| 1322 | return parser.close() |
| 1323 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1324 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1325 | def XMLID(text, parser=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1326 | """Parse XML document from string constant for its IDs. |
| 1327 | |
| 1328 | *text* is a string containing XML data, *parser* is an |
| 1329 | optional parser instance, defaulting to the standard XMLParser. |
| 1330 | |
| 1331 | Returns an (Element, dict) tuple, in which the |
| 1332 | dict maps element id:s to elements. |
| 1333 | |
| 1334 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1335 | if not parser: |
| 1336 | parser = XMLParser(target=TreeBuilder()) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1337 | parser.feed(text) |
| 1338 | tree = parser.close() |
| 1339 | ids = {} |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1340 | for elem in tree.iter(): |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1341 | id = elem.get("id") |
| 1342 | if id: |
| 1343 | ids[id] = elem |
| 1344 | return tree, ids |
| 1345 | |
Victor Stinner | 765531d | 2013-03-26 01:11:54 +0100 | [diff] [blame] | 1346 | # Parse XML document from string constant. Alias for XML(). |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1347 | fromstring = XML |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1348 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1349 | def fromstringlist(sequence, parser=None): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1350 | """Parse XML document from sequence of string fragments. |
| 1351 | |
| 1352 | *sequence* is a list of other sequence, *parser* is an optional parser |
| 1353 | instance, defaulting to the standard XMLParser. |
| 1354 | |
| 1355 | Returns an Element instance. |
| 1356 | |
| 1357 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1358 | if not parser: |
| 1359 | parser = XMLParser(target=TreeBuilder()) |
| 1360 | for text in sequence: |
| 1361 | parser.feed(text) |
| 1362 | return parser.close() |
| 1363 | |
| 1364 | # -------------------------------------------------------------------- |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1365 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1366 | |
| 1367 | class TreeBuilder: |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1368 | """Generic element structure builder. |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1369 | |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1370 | This builder converts a sequence of start, data, and end method |
| 1371 | calls to a well-formed element structure. |
| 1372 | |
| 1373 | You can use this class to build an element structure using a custom XML |
| 1374 | parser, or a parser for some other XML-like format. |
| 1375 | |
| 1376 | *element_factory* is an optional element factory which is called |
| 1377 | to create new Element instances, as necessary. |
| 1378 | |
| 1379 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1380 | def __init__(self, element_factory=None): |
| 1381 | self._data = [] # data collector |
| 1382 | self._elem = [] # element stack |
| 1383 | self._last = None # last element |
| 1384 | self._tail = None # true if we're after an end tag |
| 1385 | if element_factory is None: |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1386 | element_factory = Element |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1387 | self._factory = element_factory |
| 1388 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1389 | def close(self): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1390 | """Flush builder buffers and return toplevel document Element.""" |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1391 | assert len(self._elem) == 0, "missing end tags" |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1392 | assert self._last is not None, "missing toplevel element" |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1393 | return self._last |
| 1394 | |
| 1395 | def _flush(self): |
| 1396 | if self._data: |
| 1397 | if self._last is not None: |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 1398 | text = "".join(self._data) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1399 | if self._tail: |
| 1400 | assert self._last.tail is None, "internal error (tail)" |
| 1401 | self._last.tail = text |
| 1402 | else: |
| 1403 | assert self._last.text is None, "internal error (text)" |
| 1404 | self._last.text = text |
| 1405 | self._data = [] |
| 1406 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1407 | def data(self, data): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1408 | """Add text to current element.""" |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1409 | self._data.append(data) |
| 1410 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1411 | def start(self, tag, attrs): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1412 | """Open new element and return it. |
| 1413 | |
| 1414 | *tag* is the element name, *attrs* is a dict containing element |
| 1415 | attributes. |
| 1416 | |
| 1417 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1418 | self._flush() |
| 1419 | self._last = elem = self._factory(tag, attrs) |
| 1420 | if self._elem: |
| 1421 | self._elem[-1].append(elem) |
| 1422 | self._elem.append(elem) |
| 1423 | self._tail = 0 |
| 1424 | return elem |
| 1425 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1426 | def end(self, tag): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1427 | """Close and return current Element. |
| 1428 | |
| 1429 | *tag* is the element name. |
| 1430 | |
| 1431 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1432 | self._flush() |
| 1433 | self._last = self._elem.pop() |
| 1434 | assert self._last.tag == tag,\ |
| 1435 | "end tag mismatch (expected %s, got %s)" % ( |
| 1436 | self._last.tag, tag) |
| 1437 | self._tail = 1 |
| 1438 | return self._last |
| 1439 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1440 | |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1441 | # also see ElementTree and TreeBuilder |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1442 | class XMLParser: |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1443 | """Element structure builder for XML source data based on the expat parser. |
| 1444 | |
| 1445 | *html* are predefined HTML entities (not supported currently), |
| 1446 | *target* is an optional target object which defaults to an instance of the |
| 1447 | standard TreeBuilder class, *encoding* is an optional encoding string |
| 1448 | which if given, overrides the encoding specified in the XML file: |
| 1449 | http://www.iana.org/assignments/character-sets |
| 1450 | |
| 1451 | """ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1452 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1453 | def __init__(self, html=0, target=None, encoding=None): |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1454 | try: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1455 | from xml.parsers import expat |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 1456 | except ImportError: |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1457 | try: |
| 1458 | import pyexpat as expat |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 1459 | except ImportError: |
| 1460 | raise ImportError( |
| 1461 | "No module named expat; use SimpleXMLTreeBuilder instead" |
| 1462 | ) |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1463 | parser = expat.ParserCreate(encoding, "}") |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1464 | if target is None: |
| 1465 | target = TreeBuilder() |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1466 | # underscored names are provided for compatibility only |
| 1467 | self.parser = self._parser = parser |
| 1468 | self.target = self._target = target |
| 1469 | self._error = expat.error |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1470 | self._names = {} # name memo cache |
Florent Xicluna | 75b5e7e | 2012-03-05 10:42:19 +0100 | [diff] [blame] | 1471 | # main callbacks |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1472 | parser.DefaultHandlerExpand = self._default |
Florent Xicluna | 75b5e7e | 2012-03-05 10:42:19 +0100 | [diff] [blame] | 1473 | if hasattr(target, 'start'): |
| 1474 | parser.StartElementHandler = self._start |
| 1475 | if hasattr(target, 'end'): |
| 1476 | parser.EndElementHandler = self._end |
| 1477 | if hasattr(target, 'data'): |
| 1478 | parser.CharacterDataHandler = target.data |
| 1479 | # miscellaneous callbacks |
| 1480 | if hasattr(target, 'comment'): |
| 1481 | parser.CommentHandler = target.comment |
| 1482 | if hasattr(target, 'pi'): |
| 1483 | parser.ProcessingInstructionHandler = target.pi |
Eli Bendersky | 6206a7e | 2013-08-25 18:58:18 -0700 | [diff] [blame] | 1484 | # Configure pyexpat: buffering, new-style attribute handling. |
| 1485 | parser.buffer_text = 1 |
| 1486 | parser.ordered_attributes = 1 |
| 1487 | parser.specified_attributes = 1 |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1488 | self._doctype = None |
| 1489 | self.entity = {} |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1490 | try: |
| 1491 | self.version = "Expat %d.%d.%d" % expat.version_info |
| 1492 | except AttributeError: |
| 1493 | pass # unknown |
| 1494 | |
Eli Bendersky | 3a4fbd8 | 2013-05-19 09:01:49 -0700 | [diff] [blame] | 1495 | def _setevents(self, events_queue, events_to_report): |
Eli Bendersky | b586934 | 2013-08-30 05:51:20 -0700 | [diff] [blame] | 1496 | # Internal API for XMLPullParser |
Eli Bendersky | 3a4fbd8 | 2013-05-19 09:01:49 -0700 | [diff] [blame] | 1497 | # events_to_report: a list of events to report during parsing (same as |
Eli Bendersky | b586934 | 2013-08-30 05:51:20 -0700 | [diff] [blame] | 1498 | # the *events* of XMLPullParser's constructor. |
Eli Bendersky | 3a4fbd8 | 2013-05-19 09:01:49 -0700 | [diff] [blame] | 1499 | # events_queue: a list of actual parsing events that will be populated |
| 1500 | # by the underlying parser. |
| 1501 | # |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1502 | parser = self._parser |
Eli Bendersky | 3a4fbd8 | 2013-05-19 09:01:49 -0700 | [diff] [blame] | 1503 | append = events_queue.append |
| 1504 | for event_name in events_to_report: |
| 1505 | if event_name == "start": |
Eli Bendersky | c9f5ca2 | 2013-04-20 09:11:37 -0700 | [diff] [blame] | 1506 | parser.ordered_attributes = 1 |
| 1507 | parser.specified_attributes = 1 |
Eli Bendersky | 3a4fbd8 | 2013-05-19 09:01:49 -0700 | [diff] [blame] | 1508 | def handler(tag, attrib_in, event=event_name, append=append, |
Eli Bendersky | 6206a7e | 2013-08-25 18:58:18 -0700 | [diff] [blame] | 1509 | start=self._start): |
Eli Bendersky | c9f5ca2 | 2013-04-20 09:11:37 -0700 | [diff] [blame] | 1510 | append((event, start(tag, attrib_in))) |
| 1511 | parser.StartElementHandler = handler |
Eli Bendersky | 3a4fbd8 | 2013-05-19 09:01:49 -0700 | [diff] [blame] | 1512 | elif event_name == "end": |
| 1513 | def handler(tag, event=event_name, append=append, |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1514 | end=self._end): |
| 1515 | append((event, end(tag))) |
| 1516 | parser.EndElementHandler = handler |
Eli Bendersky | 3a4fbd8 | 2013-05-19 09:01:49 -0700 | [diff] [blame] | 1517 | elif event_name == "start-ns": |
| 1518 | def handler(prefix, uri, event=event_name, append=append): |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1519 | append((event, (prefix or "", uri or ""))) |
| 1520 | parser.StartNamespaceDeclHandler = handler |
Eli Bendersky | 3a4fbd8 | 2013-05-19 09:01:49 -0700 | [diff] [blame] | 1521 | elif event_name == "end-ns": |
| 1522 | def handler(prefix, event=event_name, append=append): |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1523 | append((event, None)) |
| 1524 | parser.EndNamespaceDeclHandler = handler |
| 1525 | else: |
Eli Bendersky | 3a4fbd8 | 2013-05-19 09:01:49 -0700 | [diff] [blame] | 1526 | raise ValueError("unknown event %r" % event_name) |
Antoine Pitrou | 5b235d0 | 2013-04-18 19:37:06 +0200 | [diff] [blame] | 1527 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 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 Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1533 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1534 | 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öwis | f30bb0e | 2007-07-28 11:40:46 +0000 | [diff] [blame] | 1542 | self._names[key] = name |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1543 | return name |
| 1544 | |
Eli Bendersky | 6206a7e | 2013-08-25 18:58:18 -0700 | [diff] [blame] | 1545 | def _start(self, tag, attr_list): |
| 1546 | # Handler for expat's StartElementHandler. Since ordered_attributes |
| 1547 | # is set, the attributes are reported as a list of alternating |
| 1548 | # attribute name,value. |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1549 | fixname = self._fixname |
| 1550 | tag = fixname(tag) |
| 1551 | attrib = {} |
Eli Bendersky | 6206a7e | 2013-08-25 18:58:18 -0700 | [diff] [blame] | 1552 | if attr_list: |
| 1553 | for i in range(0, len(attr_list), 2): |
| 1554 | attrib[fixname(attr_list[i])] = attr_list[i+1] |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1555 | return self.target.start(tag, attrib) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1556 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1557 | def _end(self, tag): |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1558 | return self.target.end(self._fixname(tag)) |
| 1559 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1560 | def _default(self, text): |
| 1561 | prefix = text[:1] |
| 1562 | if prefix == "&": |
| 1563 | # deal with undefined entities |
| 1564 | try: |
Florent Xicluna | 75b5e7e | 2012-03-05 10:42:19 +0100 | [diff] [blame] | 1565 | data_handler = self.target.data |
| 1566 | except AttributeError: |
| 1567 | return |
| 1568 | try: |
| 1569 | data_handler(self.entity[text[1:-1]]) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1570 | except KeyError: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1571 | from xml.parsers import expat |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1572 | err = expat.error( |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1573 | "undefined entity %s: line %d, column %d" % |
Florent Xicluna | 75b5e7e | 2012-03-05 10:42:19 +0100 | [diff] [blame] | 1574 | (text, self.parser.ErrorLineNumber, |
| 1575 | self.parser.ErrorColumnNumber) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1576 | ) |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1577 | err.code = 11 # XML_ERROR_UNDEFINED_ENTITY |
Florent Xicluna | 75b5e7e | 2012-03-05 10:42:19 +0100 | [diff] [blame] | 1578 | err.lineno = self.parser.ErrorLineNumber |
| 1579 | err.offset = self.parser.ErrorColumnNumber |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1580 | raise err |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1581 | elif prefix == "<" and text[:9] == "<!DOCTYPE": |
| 1582 | self._doctype = [] # inside a doctype declaration |
| 1583 | elif self._doctype is not None: |
| 1584 | # parse doctype contents |
| 1585 | if prefix == ">": |
| 1586 | self._doctype = None |
| 1587 | return |
Neal Norwitz | 9d72bb4 | 2007-04-17 08:48:32 +0000 | [diff] [blame] | 1588 | text = text.strip() |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1589 | if not text: |
| 1590 | return |
| 1591 | self._doctype.append(text) |
| 1592 | n = len(self._doctype) |
| 1593 | if n > 2: |
| 1594 | type = self._doctype[1] |
| 1595 | if type == "PUBLIC" and n == 4: |
| 1596 | name, type, pubid, system = self._doctype |
Florent Xicluna | a1c974a | 2012-07-07 13:16:44 +0200 | [diff] [blame] | 1597 | if pubid: |
| 1598 | pubid = pubid[1:-1] |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1599 | elif type == "SYSTEM" and n == 3: |
| 1600 | name, type, system = self._doctype |
| 1601 | pubid = None |
| 1602 | else: |
| 1603 | return |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1604 | if hasattr(self.target, "doctype"): |
| 1605 | self.target.doctype(name, pubid, system[1:-1]) |
Florent Xicluna | 75b5e7e | 2012-03-05 10:42:19 +0100 | [diff] [blame] | 1606 | elif self.doctype != self._XMLParser__doctype: |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1607 | # warn about deprecated call |
| 1608 | self._XMLParser__doctype(name, pubid, system[1:-1]) |
| 1609 | self.doctype(name, pubid, system[1:-1]) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1610 | self._doctype = None |
| 1611 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1612 | def doctype(self, name, pubid, system): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1613 | """(Deprecated) Handle doctype declaration |
| 1614 | |
| 1615 | *name* is the Doctype name, *pubid* is the public identifier, |
| 1616 | and *system* is the system identifier. |
| 1617 | |
| 1618 | """ |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1619 | warnings.warn( |
| 1620 | "This method of XMLParser is deprecated. Define doctype() " |
| 1621 | "method on the TreeBuilder target.", |
| 1622 | DeprecationWarning, |
| 1623 | ) |
| 1624 | |
| 1625 | # sentinel, if doctype is redefined in a subclass |
| 1626 | __doctype = doctype |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1627 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1628 | def feed(self, data): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1629 | """Feed encoded data to parser.""" |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1630 | try: |
Florent Xicluna | 75b5e7e | 2012-03-05 10:42:19 +0100 | [diff] [blame] | 1631 | self.parser.Parse(data, 0) |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1632 | except self._error as v: |
| 1633 | self._raiseerror(v) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1634 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1635 | def close(self): |
Eli Bendersky | 84fae78 | 2013-03-09 07:12:48 -0800 | [diff] [blame] | 1636 | """Finish feeding data to parser and return element structure.""" |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1637 | try: |
Florent Xicluna | 75b5e7e | 2012-03-05 10:42:19 +0100 | [diff] [blame] | 1638 | self.parser.Parse("", 1) # end of data |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 1639 | except self._error as v: |
| 1640 | self._raiseerror(v) |
Florent Xicluna | 75b5e7e | 2012-03-05 10:42:19 +0100 | [diff] [blame] | 1641 | try: |
Florent Xicluna | fb06746 | 2012-03-05 11:42:49 +0100 | [diff] [blame] | 1642 | close_handler = self.target.close |
| 1643 | except AttributeError: |
| 1644 | pass |
| 1645 | else: |
| 1646 | return close_handler() |
Florent Xicluna | 75b5e7e | 2012-03-05 10:42:19 +0100 | [diff] [blame] | 1647 | finally: |
| 1648 | # get rid of circular references |
| 1649 | del self.parser, self._parser |
| 1650 | del self.target, self._target |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1651 | |
Florent Xicluna | a72a98f | 2012-02-13 11:03:30 +0100 | [diff] [blame] | 1652 | |
| 1653 | # Import the C accelerators |
| 1654 | try: |
Eli Bendersky | 46955b2 | 2013-05-19 09:20:50 -0700 | [diff] [blame] | 1655 | # Element is going to be shadowed by the C implementation. We need to keep |
| 1656 | # the Python version of it accessible for some "creative" by external code |
| 1657 | # (see tests) |
| 1658 | _Element_Py = Element |
| 1659 | |
Florent Xicluna | a72a98f | 2012-02-13 11:03:30 +0100 | [diff] [blame] | 1660 | # Element, SubElement, ParseError, TreeBuilder, XMLParser |
| 1661 | from _elementtree import * |
Eli Bendersky | c4e98a6 | 2013-05-19 09:24:43 -0700 | [diff] [blame] | 1662 | except ImportError: |
| 1663 | pass |