ElementTree.py 56 KB

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