ElementTree.py 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085
  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 https://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. "indent", "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. "canonicalize", "C14NWriterTarget",
  76. ]
  77. VERSION = "1.3.0"
  78. import sys
  79. import re
  80. import warnings
  81. import io
  82. import collections
  83. import collections.abc
  84. import contextlib
  85. import weakref
  86. from . import ElementPath
  87. class ParseError(SyntaxError):
  88. """An error when parsing an XML document.
  89. In addition to its exception value, a ParseError contains
  90. two extra attributes:
  91. 'code' - the specific exception code
  92. 'position' - the line and column of the error
  93. """
  94. pass
  95. # --------------------------------------------------------------------
  96. def iselement(element):
  97. """Return True if *element* appears to be an Element."""
  98. return hasattr(element, 'tag')
  99. class Element:
  100. """An XML element.
  101. This class is the reference implementation of the Element interface.
  102. An element's length is its number of subelements. That means if you
  103. want to check if an element is truly empty, you should check BOTH
  104. its length AND its text attribute.
  105. The element tag, attribute names, and attribute values can be either
  106. bytes or strings.
  107. *tag* is the element name. *attrib* is an optional dictionary containing
  108. element attributes. *extra* are additional element attributes given as
  109. keyword arguments.
  110. Example form:
  111. <tag attrib>text<child/>...</tag>tail
  112. """
  113. tag = None
  114. """The element's name."""
  115. attrib = None
  116. """Dictionary of the element's attributes."""
  117. text = None
  118. """
  119. Text before first subelement. This is either a string or the value None.
  120. Note that if there is no text, this attribute may be either
  121. None or the empty string, depending on the parser.
  122. """
  123. tail = None
  124. """
  125. Text after this element's end tag, but before the next sibling element's
  126. start tag. This is either a string or the value None. Note that if there
  127. was no text, this attribute may be either None or an empty string,
  128. depending on the parser.
  129. """
  130. def __init__(self, tag, attrib={}, **extra):
  131. if not isinstance(attrib, dict):
  132. raise TypeError("attrib must be dict, not %s" % (
  133. attrib.__class__.__name__,))
  134. self.tag = tag
  135. self.attrib = {**attrib, **extra}
  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. elem = self.makeelement(self.tag, self.attrib)
  148. elem.text = self.text
  149. elem.tail = self.tail
  150. elem[:] = self
  151. return elem
  152. def __len__(self):
  153. return len(self._children)
  154. def __bool__(self):
  155. warnings.warn(
  156. "Testing an element's truth value will always return True in "
  157. "future versions. "
  158. "Use specific 'len(elem)' or 'elem is not None' test instead.",
  159. DeprecationWarning, stacklevel=2
  160. )
  161. return len(self._children) != 0 # emulate old behaviour, for now
  162. def __getitem__(self, index):
  163. return self._children[index]
  164. def __setitem__(self, index, element):
  165. if isinstance(index, slice):
  166. for elt in element:
  167. self._assert_is_element(elt)
  168. else:
  169. self._assert_is_element(element)
  170. self._children[index] = element
  171. def __delitem__(self, index):
  172. del self._children[index]
  173. def append(self, subelement):
  174. """Add *subelement* to the end of this element.
  175. The new element will appear in document order after the last existing
  176. subelement (or directly after the text, if it's the first subelement),
  177. but before the end tag for this element.
  178. """
  179. self._assert_is_element(subelement)
  180. self._children.append(subelement)
  181. def extend(self, elements):
  182. """Append subelements from a sequence.
  183. *elements* is a sequence with zero or more elements.
  184. """
  185. for element in elements:
  186. self._assert_is_element(element)
  187. self._children.append(element)
  188. def insert(self, index, subelement):
  189. """Insert *subelement* at position *index*."""
  190. self._assert_is_element(subelement)
  191. self._children.insert(index, subelement)
  192. def _assert_is_element(self, e):
  193. # Need to refer to the actual Python implementation, not the
  194. # shadowing C implementation.
  195. if not isinstance(e, _Element_Py):
  196. raise TypeError('expected an Element, not %s' % type(e).__name__)
  197. def remove(self, subelement):
  198. """Remove matching subelement.
  199. Unlike the find methods, this method compares elements based on
  200. identity, NOT ON tag value or contents. To remove subelements by
  201. other means, the easiest way is to use a list comprehension to
  202. select what elements to keep, and then use slice assignment to update
  203. the parent element.
  204. ValueError is raised if a matching element could not be found.
  205. """
  206. # assert iselement(element)
  207. self._children.remove(subelement)
  208. def find(self, path, namespaces=None):
  209. """Find first matching element by tag name or path.
  210. *path* is a string having either an element tag or an XPath,
  211. *namespaces* is an optional mapping from namespace prefix to full name.
  212. Return the first matching element, or None if no element was found.
  213. """
  214. return ElementPath.find(self, path, namespaces)
  215. def findtext(self, path, default=None, namespaces=None):
  216. """Find text for first matching element by tag name or path.
  217. *path* is a string having either an element tag or an XPath,
  218. *default* is the value to return if the element was not found,
  219. *namespaces* is an optional mapping from namespace prefix to full name.
  220. Return text content of first matching element, or default value if
  221. none was found. Note that if an element is found having no text
  222. content, the empty string is returned.
  223. """
  224. return ElementPath.findtext(self, path, default, namespaces)
  225. def findall(self, path, namespaces=None):
  226. """Find all matching subelements by tag name or path.
  227. *path* is a string having either an element tag or an XPath,
  228. *namespaces* is an optional mapping from namespace prefix to full name.
  229. Returns list containing all matching elements in document order.
  230. """
  231. return ElementPath.findall(self, path, namespaces)
  232. def iterfind(self, path, namespaces=None):
  233. """Find all matching subelements by tag name or path.
  234. *path* is a string having either an element tag or an XPath,
  235. *namespaces* is an optional mapping from namespace prefix to full name.
  236. Return an iterable yielding all matching elements in document order.
  237. """
  238. return ElementPath.iterfind(self, path, namespaces)
  239. def clear(self):
  240. """Reset element.
  241. This function removes all subelements, clears all attributes, and sets
  242. the text and tail attributes to None.
  243. """
  244. self.attrib.clear()
  245. self._children = []
  246. self.text = self.tail = None
  247. def get(self, key, default=None):
  248. """Get element attribute.
  249. Equivalent to attrib.get, but some implementations may handle this a
  250. bit more efficiently. *key* is what attribute to look for, and
  251. *default* is what to return if the attribute was not found.
  252. Returns a string containing the attribute value, or the default if
  253. attribute was not found.
  254. """
  255. return self.attrib.get(key, default)
  256. def set(self, key, value):
  257. """Set element attribute.
  258. Equivalent to attrib[key] = value, but some implementations may handle
  259. this a bit more efficiently. *key* is what attribute to set, and
  260. *value* is the attribute value to set it to.
  261. """
  262. self.attrib[key] = value
  263. def keys(self):
  264. """Get list of attribute names.
  265. Names are returned in an arbitrary order, just like an ordinary
  266. Python dict. Equivalent to attrib.keys()
  267. """
  268. return self.attrib.keys()
  269. def items(self):
  270. """Get element attributes as a sequence.
  271. The attributes are returned in arbitrary order. Equivalent to
  272. attrib.items().
  273. Return a list of (name, value) tuples.
  274. """
  275. return self.attrib.items()
  276. def iter(self, tag=None):
  277. """Create tree iterator.
  278. The iterator loops over the element and all subelements in document
  279. order, returning all elements with a matching tag.
  280. If the tree structure is modified during iteration, new or removed
  281. elements may or may not be included. To get a stable set, use the
  282. list() function on the iterator, and loop over the resulting list.
  283. *tag* is what tags to look for (default is to return all elements)
  284. Return an iterator containing all the matching elements.
  285. """
  286. if tag == "*":
  287. tag = None
  288. if tag is None or self.tag == tag:
  289. yield self
  290. for e in self._children:
  291. yield from e.iter(tag)
  292. def itertext(self):
  293. """Create text iterator.
  294. The iterator loops over the element and all subelements in document
  295. order, returning all inner text.
  296. """
  297. tag = self.tag
  298. if not isinstance(tag, str) and tag is not None:
  299. return
  300. t = self.text
  301. if t:
  302. yield t
  303. for e in self:
  304. yield from e.itertext()
  305. t = e.tail
  306. if t:
  307. yield t
  308. def SubElement(parent, tag, attrib={}, **extra):
  309. """Subelement factory which creates an element instance, and appends it
  310. to an existing parent.
  311. The element tag, attribute names, and attribute values can be either
  312. bytes or Unicode strings.
  313. *parent* is the parent element, *tag* is the subelements name, *attrib* is
  314. an optional directory containing element attributes, *extra* are
  315. additional attributes given as keyword arguments.
  316. """
  317. attrib = {**attrib, **extra}
  318. element = parent.makeelement(tag, attrib)
  319. parent.append(element)
  320. return element
  321. def Comment(text=None):
  322. """Comment element factory.
  323. This function creates a special element which the standard serializer
  324. serializes as an XML comment.
  325. *text* is a string containing the comment string.
  326. """
  327. element = Element(Comment)
  328. element.text = text
  329. return element
  330. def ProcessingInstruction(target, text=None):
  331. """Processing Instruction element factory.
  332. This function creates a special element which the standard serializer
  333. serializes as an XML comment.
  334. *target* is a string containing the processing instruction, *text* is a
  335. string containing the processing instruction contents, if any.
  336. """
  337. element = Element(ProcessingInstruction)
  338. element.text = target
  339. if text:
  340. element.text = element.text + " " + text
  341. return element
  342. PI = ProcessingInstruction
  343. class QName:
  344. """Qualified name wrapper.
  345. This class can be used to wrap a QName attribute value in order to get
  346. proper namespace handing on output.
  347. *text_or_uri* is a string containing the QName value either in the form
  348. {uri}local, or if the tag argument is given, the URI part of a QName.
  349. *tag* is an optional argument which if given, will make the first
  350. argument (text_or_uri) be interpreted as a URI, and this argument (tag)
  351. be interpreted as a local name.
  352. """
  353. def __init__(self, text_or_uri, tag=None):
  354. if tag:
  355. text_or_uri = "{%s}%s" % (text_or_uri, tag)
  356. self.text = text_or_uri
  357. def __str__(self):
  358. return self.text
  359. def __repr__(self):
  360. return '<%s %r>' % (self.__class__.__name__, self.text)
  361. def __hash__(self):
  362. return hash(self.text)
  363. def __le__(self, other):
  364. if isinstance(other, QName):
  365. return self.text <= other.text
  366. return self.text <= other
  367. def __lt__(self, other):
  368. if isinstance(other, QName):
  369. return self.text < other.text
  370. return self.text < other
  371. def __ge__(self, other):
  372. if isinstance(other, QName):
  373. return self.text >= other.text
  374. return self.text >= other
  375. def __gt__(self, other):
  376. if isinstance(other, QName):
  377. return self.text > other.text
  378. return self.text > other
  379. def __eq__(self, other):
  380. if isinstance(other, QName):
  381. return self.text == other.text
  382. return self.text == other
  383. # --------------------------------------------------------------------
  384. class ElementTree:
  385. """An XML element hierarchy.
  386. This class also provides support for serialization to and from
  387. standard XML.
  388. *element* is an optional root element node,
  389. *file* is an optional file handle or file name of an XML file whose
  390. contents will be used to initialize the tree with.
  391. """
  392. def __init__(self, element=None, file=None):
  393. # assert element is None or iselement(element)
  394. self._root = element # first node
  395. if file:
  396. self.parse(file)
  397. def getroot(self):
  398. """Return root element of this tree."""
  399. return self._root
  400. def _setroot(self, element):
  401. """Replace root element of this tree.
  402. This will discard the current contents of the tree and replace it
  403. with the given element. Use with care!
  404. """
  405. # assert iselement(element)
  406. self._root = element
  407. def parse(self, source, parser=None):
  408. """Load external XML document into element tree.
  409. *source* is a file name or file object, *parser* is an optional parser
  410. instance that defaults to XMLParser.
  411. ParseError is raised if the parser fails to parse the document.
  412. Returns the root element of the given source document.
  413. """
  414. close_source = False
  415. if not hasattr(source, "read"):
  416. source = open(source, "rb")
  417. close_source = True
  418. try:
  419. if parser is None:
  420. # If no parser was specified, create a default XMLParser
  421. parser = XMLParser()
  422. if hasattr(parser, '_parse_whole'):
  423. # The default XMLParser, when it comes from an accelerator,
  424. # can define an internal _parse_whole API for efficiency.
  425. # It can be used to parse the whole source without feeding
  426. # it with chunks.
  427. self._root = parser._parse_whole(source)
  428. return self._root
  429. while data := source.read(65536):
  430. parser.feed(data)
  431. self._root = parser.close()
  432. return self._root
  433. finally:
  434. if close_source:
  435. source.close()
  436. def iter(self, tag=None):
  437. """Create and return tree iterator for the root element.
  438. The iterator loops over all elements in this tree, in document order.
  439. *tag* is a string with the tag name to iterate over
  440. (default is to return all elements).
  441. """
  442. # assert self._root is not None
  443. return self._root.iter(tag)
  444. def find(self, path, namespaces=None):
  445. """Find first matching element by tag name or path.
  446. Same as getroot().find(path), which is Element.find()
  447. *path* is a string having either an element tag or an XPath,
  448. *namespaces* is an optional mapping from namespace prefix to full name.
  449. Return the first matching element, or None if no element was found.
  450. """
  451. # assert self._root is not None
  452. if path[:1] == "/":
  453. path = "." + path
  454. warnings.warn(
  455. "This search is broken in 1.3 and earlier, and will be "
  456. "fixed in a future version. If you rely on the current "
  457. "behaviour, change it to %r" % path,
  458. FutureWarning, stacklevel=2
  459. )
  460. return self._root.find(path, namespaces)
  461. def findtext(self, path, default=None, namespaces=None):
  462. """Find first matching element by tag name or path.
  463. Same as getroot().findtext(path), which is Element.findtext()
  464. *path* is a string having either an element tag or an XPath,
  465. *namespaces* is an optional mapping from namespace prefix to full name.
  466. Return the first matching element, or None if no element was found.
  467. """
  468. # assert self._root is not None
  469. if path[:1] == "/":
  470. path = "." + path
  471. warnings.warn(
  472. "This search is broken in 1.3 and earlier, and will be "
  473. "fixed in a future version. If you rely on the current "
  474. "behaviour, change it to %r" % path,
  475. FutureWarning, stacklevel=2
  476. )
  477. return self._root.findtext(path, default, namespaces)
  478. def findall(self, path, namespaces=None):
  479. """Find all matching subelements by tag name or path.
  480. Same as getroot().findall(path), which is Element.findall().
  481. *path* is a string having either an element tag or an XPath,
  482. *namespaces* is an optional mapping from namespace prefix to full name.
  483. Return list containing all matching elements in document order.
  484. """
  485. # assert self._root is not None
  486. if path[:1] == "/":
  487. path = "." + path
  488. warnings.warn(
  489. "This search is broken in 1.3 and earlier, and will be "
  490. "fixed in a future version. If you rely on the current "
  491. "behaviour, change it to %r" % path,
  492. FutureWarning, stacklevel=2
  493. )
  494. return self._root.findall(path, namespaces)
  495. def iterfind(self, path, namespaces=None):
  496. """Find all matching subelements by tag name or path.
  497. Same as getroot().iterfind(path), which is element.iterfind()
  498. *path* is a string having either an element tag or an XPath,
  499. *namespaces* is an optional mapping from namespace prefix to full name.
  500. Return an iterable yielding all matching elements in document order.
  501. """
  502. # assert self._root is not None
  503. if path[:1] == "/":
  504. path = "." + path
  505. warnings.warn(
  506. "This search is broken in 1.3 and earlier, and will be "
  507. "fixed in a future version. If you rely on the current "
  508. "behaviour, change it to %r" % path,
  509. FutureWarning, stacklevel=2
  510. )
  511. return self._root.iterfind(path, namespaces)
  512. def write(self, file_or_filename,
  513. encoding=None,
  514. xml_declaration=None,
  515. default_namespace=None,
  516. method=None, *,
  517. short_empty_elements=True):
  518. """Write element tree to a file as XML.
  519. Arguments:
  520. *file_or_filename* -- file name or a file object opened for writing
  521. *encoding* -- the output encoding (default: US-ASCII)
  522. *xml_declaration* -- bool indicating if an XML declaration should be
  523. added to the output. If None, an XML declaration
  524. is added if encoding IS NOT either of:
  525. US-ASCII, UTF-8, or Unicode
  526. *default_namespace* -- sets the default XML namespace (for "xmlns")
  527. *method* -- either "xml" (default), "html, "text", or "c14n"
  528. *short_empty_elements* -- controls the formatting of elements
  529. that contain no content. If True (default)
  530. they are emitted as a single self-closed
  531. tag, otherwise they are emitted as a pair
  532. of start/end tags
  533. """
  534. if not method:
  535. method = "xml"
  536. elif method not in _serialize:
  537. raise ValueError("unknown method %r" % method)
  538. if not encoding:
  539. if method == "c14n":
  540. encoding = "utf-8"
  541. else:
  542. encoding = "us-ascii"
  543. with _get_writer(file_or_filename, encoding) as (write, declared_encoding):
  544. if method == "xml" and (xml_declaration or
  545. (xml_declaration is None and
  546. encoding.lower() != "unicode" and
  547. declared_encoding.lower() not in ("utf-8", "us-ascii"))):
  548. write("<?xml version='1.0' encoding='%s'?>\n" % (
  549. declared_encoding,))
  550. if method == "text":
  551. _serialize_text(write, self._root)
  552. else:
  553. qnames, namespaces = _namespaces(self._root, default_namespace)
  554. serialize = _serialize[method]
  555. serialize(write, self._root, qnames, namespaces,
  556. short_empty_elements=short_empty_elements)
  557. def write_c14n(self, file):
  558. # lxml.etree compatibility. use output method instead
  559. return self.write(file, method="c14n")
  560. # --------------------------------------------------------------------
  561. # serialization support
  562. @contextlib.contextmanager
  563. def _get_writer(file_or_filename, encoding):
  564. # returns text write method and release all resources after using
  565. try:
  566. write = file_or_filename.write
  567. except AttributeError:
  568. # file_or_filename is a file name
  569. if encoding.lower() == "unicode":
  570. encoding="utf-8"
  571. with open(file_or_filename, "w", encoding=encoding,
  572. errors="xmlcharrefreplace") as file:
  573. yield file.write, encoding
  574. else:
  575. # file_or_filename is a file-like object
  576. # encoding determines if it is a text or binary writer
  577. if encoding.lower() == "unicode":
  578. # use a text writer as is
  579. yield write, getattr(file_or_filename, "encoding", None) or "utf-8"
  580. else:
  581. # wrap a binary writer with TextIOWrapper
  582. with contextlib.ExitStack() as stack:
  583. if isinstance(file_or_filename, io.BufferedIOBase):
  584. file = file_or_filename
  585. elif isinstance(file_or_filename, io.RawIOBase):
  586. file = io.BufferedWriter(file_or_filename)
  587. # Keep the original file open when the BufferedWriter is
  588. # destroyed
  589. stack.callback(file.detach)
  590. else:
  591. # This is to handle passed objects that aren't in the
  592. # IOBase hierarchy, but just have a write method
  593. file = io.BufferedIOBase()
  594. file.writable = lambda: True
  595. file.write = write
  596. try:
  597. # TextIOWrapper uses this methods to determine
  598. # if BOM (for UTF-16, etc) should be added
  599. file.seekable = file_or_filename.seekable
  600. file.tell = file_or_filename.tell
  601. except AttributeError:
  602. pass
  603. file = io.TextIOWrapper(file,
  604. encoding=encoding,
  605. errors="xmlcharrefreplace",
  606. newline="\n")
  607. # Keep the original file open when the TextIOWrapper is
  608. # destroyed
  609. stack.callback(file.detach)
  610. yield file.write, encoding
  611. def _namespaces(elem, default_namespace=None):
  612. # identify namespaces used in this tree
  613. # maps qnames to *encoded* prefix:local names
  614. qnames = {None: None}
  615. # maps uri:s to prefixes
  616. namespaces = {}
  617. if default_namespace:
  618. namespaces[default_namespace] = ""
  619. def add_qname(qname):
  620. # calculate serialized qname representation
  621. try:
  622. if qname[:1] == "{":
  623. uri, tag = qname[1:].rsplit("}", 1)
  624. prefix = namespaces.get(uri)
  625. if prefix is None:
  626. prefix = _namespace_map.get(uri)
  627. if prefix is None:
  628. prefix = "ns%d" % len(namespaces)
  629. if prefix != "xml":
  630. namespaces[uri] = prefix
  631. if prefix:
  632. qnames[qname] = "%s:%s" % (prefix, tag)
  633. else:
  634. qnames[qname] = tag # default element
  635. else:
  636. if default_namespace:
  637. # FIXME: can this be handled in XML 1.0?
  638. raise ValueError(
  639. "cannot use non-qualified names with "
  640. "default_namespace option"
  641. )
  642. qnames[qname] = qname
  643. except TypeError:
  644. _raise_serialization_error(qname)
  645. # populate qname and namespaces table
  646. for elem in elem.iter():
  647. tag = elem.tag
  648. if isinstance(tag, QName):
  649. if tag.text not in qnames:
  650. add_qname(tag.text)
  651. elif isinstance(tag, str):
  652. if tag not in qnames:
  653. add_qname(tag)
  654. elif tag is not None and tag is not Comment and tag is not PI:
  655. _raise_serialization_error(tag)
  656. for key, value in elem.items():
  657. if isinstance(key, QName):
  658. key = key.text
  659. if key not in qnames:
  660. add_qname(key)
  661. if isinstance(value, QName) and value.text not in qnames:
  662. add_qname(value.text)
  663. text = elem.text
  664. if isinstance(text, QName) and text.text not in qnames:
  665. add_qname(text.text)
  666. return qnames, namespaces
  667. def _serialize_xml(write, elem, qnames, namespaces,
  668. short_empty_elements, **kwargs):
  669. tag = elem.tag
  670. text = elem.text
  671. if tag is Comment:
  672. write("<!--%s-->" % text)
  673. elif tag is ProcessingInstruction:
  674. write("<?%s?>" % text)
  675. else:
  676. tag = qnames[tag]
  677. if tag is None:
  678. if text:
  679. write(_escape_cdata(text))
  680. for e in elem:
  681. _serialize_xml(write, e, qnames, None,
  682. short_empty_elements=short_empty_elements)
  683. else:
  684. write("<" + tag)
  685. items = list(elem.items())
  686. if items or namespaces:
  687. if namespaces:
  688. for v, k in sorted(namespaces.items(),
  689. key=lambda x: x[1]): # sort on prefix
  690. if k:
  691. k = ":" + k
  692. write(" xmlns%s=\"%s\"" % (
  693. k,
  694. _escape_attrib(v)
  695. ))
  696. for k, v in items:
  697. if isinstance(k, QName):
  698. k = k.text
  699. if isinstance(v, QName):
  700. v = qnames[v.text]
  701. else:
  702. v = _escape_attrib(v)
  703. write(" %s=\"%s\"" % (qnames[k], v))
  704. if text or len(elem) or not short_empty_elements:
  705. write(">")
  706. if text:
  707. write(_escape_cdata(text))
  708. for e in elem:
  709. _serialize_xml(write, e, qnames, None,
  710. short_empty_elements=short_empty_elements)
  711. write("</" + tag + ">")
  712. else:
  713. write(" />")
  714. if elem.tail:
  715. write(_escape_cdata(elem.tail))
  716. HTML_EMPTY = {"area", "base", "basefont", "br", "col", "embed", "frame", "hr",
  717. "img", "input", "isindex", "link", "meta", "param", "source",
  718. "track", "wbr"}
  719. def _serialize_html(write, elem, qnames, namespaces, **kwargs):
  720. tag = elem.tag
  721. text = elem.text
  722. if tag is Comment:
  723. write("<!--%s-->" % _escape_cdata(text))
  724. elif tag is ProcessingInstruction:
  725. write("<?%s?>" % _escape_cdata(text))
  726. else:
  727. tag = qnames[tag]
  728. if tag is None:
  729. if text:
  730. write(_escape_cdata(text))
  731. for e in elem:
  732. _serialize_html(write, e, qnames, None)
  733. else:
  734. write("<" + tag)
  735. items = list(elem.items())
  736. if items or namespaces:
  737. if namespaces:
  738. for v, k in sorted(namespaces.items(),
  739. key=lambda x: x[1]): # sort on prefix
  740. if k:
  741. k = ":" + k
  742. write(" xmlns%s=\"%s\"" % (
  743. k,
  744. _escape_attrib(v)
  745. ))
  746. for k, v in items:
  747. if isinstance(k, QName):
  748. k = k.text
  749. if isinstance(v, QName):
  750. v = qnames[v.text]
  751. else:
  752. v = _escape_attrib_html(v)
  753. # FIXME: handle boolean attributes
  754. write(" %s=\"%s\"" % (qnames[k], v))
  755. write(">")
  756. ltag = tag.lower()
  757. if text:
  758. if ltag == "script" or ltag == "style":
  759. write(text)
  760. else:
  761. write(_escape_cdata(text))
  762. for e in elem:
  763. _serialize_html(write, e, qnames, None)
  764. if ltag not in HTML_EMPTY:
  765. write("</" + tag + ">")
  766. if elem.tail:
  767. write(_escape_cdata(elem.tail))
  768. def _serialize_text(write, elem):
  769. for part in elem.itertext():
  770. write(part)
  771. if elem.tail:
  772. write(elem.tail)
  773. _serialize = {
  774. "xml": _serialize_xml,
  775. "html": _serialize_html,
  776. "text": _serialize_text,
  777. # this optional method is imported at the end of the module
  778. # "c14n": _serialize_c14n,
  779. }
  780. def register_namespace(prefix, uri):
  781. """Register a namespace prefix.
  782. The registry is global, and any existing mapping for either the
  783. given prefix or the namespace URI will be removed.
  784. *prefix* is the namespace prefix, *uri* is a namespace uri. Tags and
  785. attributes in this namespace will be serialized with prefix if possible.
  786. ValueError is raised if prefix is reserved or is invalid.
  787. """
  788. if re.match(r"ns\d+$", prefix):
  789. raise ValueError("Prefix format reserved for internal use")
  790. for k, v in list(_namespace_map.items()):
  791. if k == uri or v == prefix:
  792. del _namespace_map[k]
  793. _namespace_map[uri] = prefix
  794. _namespace_map = {
  795. # "well-known" namespace prefixes
  796. "http://www.w3.org/XML/1998/namespace": "xml",
  797. "http://www.w3.org/1999/xhtml": "html",
  798. "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
  799. "http://schemas.xmlsoap.org/wsdl/": "wsdl",
  800. # xml schema
  801. "http://www.w3.org/2001/XMLSchema": "xs",
  802. "http://www.w3.org/2001/XMLSchema-instance": "xsi",
  803. # dublin core
  804. "http://purl.org/dc/elements/1.1/": "dc",
  805. }
  806. # For tests and troubleshooting
  807. register_namespace._namespace_map = _namespace_map
  808. def _raise_serialization_error(text):
  809. raise TypeError(
  810. "cannot serialize %r (type %s)" % (text, type(text).__name__)
  811. )
  812. def _escape_cdata(text):
  813. # escape character data
  814. try:
  815. # it's worth avoiding do-nothing calls for strings that are
  816. # shorter than 500 characters, or so. assume that's, by far,
  817. # the most common case in most applications.
  818. if "&" in text:
  819. text = text.replace("&", "&amp;")
  820. if "<" in text:
  821. text = text.replace("<", "&lt;")
  822. if ">" in text:
  823. text = text.replace(">", "&gt;")
  824. return text
  825. except (TypeError, AttributeError):
  826. _raise_serialization_error(text)
  827. def _escape_attrib(text):
  828. # escape attribute value
  829. try:
  830. if "&" in text:
  831. text = text.replace("&", "&amp;")
  832. if "<" in text:
  833. text = text.replace("<", "&lt;")
  834. if ">" in text:
  835. text = text.replace(">", "&gt;")
  836. if "\"" in text:
  837. text = text.replace("\"", "&quot;")
  838. # Although section 2.11 of the XML specification states that CR or
  839. # CR LN should be replaced with just LN, it applies only to EOLNs
  840. # which take part of organizing file into lines. Within attributes,
  841. # we are replacing these with entity numbers, so they do not count.
  842. # http://www.w3.org/TR/REC-xml/#sec-line-ends
  843. # The current solution, contained in following six lines, was
  844. # discussed in issue 17582 and 39011.
  845. if "\r" in text:
  846. text = text.replace("\r", "&#13;")
  847. if "\n" in text:
  848. text = text.replace("\n", "&#10;")
  849. if "\t" in text:
  850. text = text.replace("\t", "&#09;")
  851. return text
  852. except (TypeError, AttributeError):
  853. _raise_serialization_error(text)
  854. def _escape_attrib_html(text):
  855. # escape attribute value
  856. try:
  857. if "&" in text:
  858. text = text.replace("&", "&amp;")
  859. if ">" in text:
  860. text = text.replace(">", "&gt;")
  861. if "\"" in text:
  862. text = text.replace("\"", "&quot;")
  863. return text
  864. except (TypeError, AttributeError):
  865. _raise_serialization_error(text)
  866. # --------------------------------------------------------------------
  867. def tostring(element, encoding=None, method=None, *,
  868. xml_declaration=None, default_namespace=None,
  869. short_empty_elements=True):
  870. """Generate string representation of XML element.
  871. All subelements are included. If encoding is "unicode", a string
  872. is returned. Otherwise a bytestring is returned.
  873. *element* is an Element instance, *encoding* is an optional output
  874. encoding defaulting to US-ASCII, *method* is an optional output which can
  875. be one of "xml" (default), "html", "text" or "c14n", *default_namespace*
  876. sets the default XML namespace (for "xmlns").
  877. Returns an (optionally) encoded string containing the XML data.
  878. """
  879. stream = io.StringIO() if encoding == 'unicode' else io.BytesIO()
  880. ElementTree(element).write(stream, encoding,
  881. xml_declaration=xml_declaration,
  882. default_namespace=default_namespace,
  883. method=method,
  884. short_empty_elements=short_empty_elements)
  885. return stream.getvalue()
  886. class _ListDataStream(io.BufferedIOBase):
  887. """An auxiliary stream accumulating into a list reference."""
  888. def __init__(self, lst):
  889. self.lst = lst
  890. def writable(self):
  891. return True
  892. def seekable(self):
  893. return True
  894. def write(self, b):
  895. self.lst.append(b)
  896. def tell(self):
  897. return len(self.lst)
  898. def tostringlist(element, encoding=None, method=None, *,
  899. xml_declaration=None, default_namespace=None,
  900. short_empty_elements=True):
  901. lst = []
  902. stream = _ListDataStream(lst)
  903. ElementTree(element).write(stream, encoding,
  904. xml_declaration=xml_declaration,
  905. default_namespace=default_namespace,
  906. method=method,
  907. short_empty_elements=short_empty_elements)
  908. return lst
  909. def dump(elem):
  910. """Write element tree or element structure to sys.stdout.
  911. This function should be used for debugging only.
  912. *elem* is either an ElementTree, or a single Element. The exact output
  913. format is implementation dependent. In this version, it's written as an
  914. ordinary XML file.
  915. """
  916. # debugging
  917. if not isinstance(elem, ElementTree):
  918. elem = ElementTree(elem)
  919. elem.write(sys.stdout, encoding="unicode")
  920. tail = elem.getroot().tail
  921. if not tail or tail[-1] != "\n":
  922. sys.stdout.write("\n")
  923. def indent(tree, space=" ", level=0):
  924. """Indent an XML document by inserting newlines and indentation space
  925. after elements.
  926. *tree* is the ElementTree or Element to modify. The (root) element
  927. itself will not be changed, but the tail text of all elements in its
  928. subtree will be adapted.
  929. *space* is the whitespace to insert for each indentation level, two
  930. space characters by default.
  931. *level* is the initial indentation level. Setting this to a higher
  932. value than 0 can be used for indenting subtrees that are more deeply
  933. nested inside of a document.
  934. """
  935. if isinstance(tree, ElementTree):
  936. tree = tree.getroot()
  937. if level < 0:
  938. raise ValueError(f"Initial indentation level must be >= 0, got {level}")
  939. if not len(tree):
  940. return
  941. # Reduce the memory consumption by reusing indentation strings.
  942. indentations = ["\n" + level * space]
  943. def _indent_children(elem, level):
  944. # Start a new indentation level for the first child.
  945. child_level = level + 1
  946. try:
  947. child_indentation = indentations[child_level]
  948. except IndexError:
  949. child_indentation = indentations[level] + space
  950. indentations.append(child_indentation)
  951. if not elem.text or not elem.text.strip():
  952. elem.text = child_indentation
  953. for child in elem:
  954. if len(child):
  955. _indent_children(child, child_level)
  956. if not child.tail or not child.tail.strip():
  957. child.tail = child_indentation
  958. # Dedent after the last child by overwriting the previous indentation.
  959. if not child.tail.strip():
  960. child.tail = indentations[level]
  961. _indent_children(tree, 0)
  962. # --------------------------------------------------------------------
  963. # parsing
  964. def parse(source, parser=None):
  965. """Parse XML document into element tree.
  966. *source* is a filename or file object containing XML data,
  967. *parser* is an optional parser instance defaulting to XMLParser.
  968. Return an ElementTree instance.
  969. """
  970. tree = ElementTree()
  971. tree.parse(source, parser)
  972. return tree
  973. def iterparse(source, events=None, parser=None):
  974. """Incrementally parse XML document into ElementTree.
  975. This class also reports what's going on to the user based on the
  976. *events* it is initialized with. The supported events are the strings
  977. "start", "end", "start-ns" and "end-ns" (the "ns" events are used to get
  978. detailed namespace information). If *events* is omitted, only
  979. "end" events are reported.
  980. *source* is a filename or file object containing XML data, *events* is
  981. a list of events to report back, *parser* is an optional parser instance.
  982. Returns an iterator providing (event, elem) pairs.
  983. """
  984. # Use the internal, undocumented _parser argument for now; When the
  985. # parser argument of iterparse is removed, this can be killed.
  986. pullparser = XMLPullParser(events=events, _parser=parser)
  987. if not hasattr(source, "read"):
  988. source = open(source, "rb")
  989. close_source = True
  990. else:
  991. close_source = False
  992. def iterator(source):
  993. try:
  994. while True:
  995. yield from pullparser.read_events()
  996. # load event buffer
  997. data = source.read(16 * 1024)
  998. if not data:
  999. break
  1000. pullparser.feed(data)
  1001. root = pullparser._close_and_return_root()
  1002. yield from pullparser.read_events()
  1003. it = wr()
  1004. if it is not None:
  1005. it.root = root
  1006. finally:
  1007. if close_source:
  1008. source.close()
  1009. class IterParseIterator(collections.abc.Iterator):
  1010. __next__ = iterator(source).__next__
  1011. def __del__(self):
  1012. if close_source:
  1013. source.close()
  1014. it = IterParseIterator()
  1015. it.root = None
  1016. wr = weakref.ref(it)
  1017. return it
  1018. class XMLPullParser:
  1019. def __init__(self, events=None, *, _parser=None):
  1020. # The _parser argument is for internal use only and must not be relied
  1021. # upon in user code. It will be removed in a future release.
  1022. # See https://bugs.python.org/issue17741 for more details.
  1023. self._events_queue = collections.deque()
  1024. self._parser = _parser or XMLParser(target=TreeBuilder())
  1025. # wire up the parser for event reporting
  1026. if events is None:
  1027. events = ("end",)
  1028. self._parser._setevents(self._events_queue, events)
  1029. def feed(self, data):
  1030. """Feed encoded data to parser."""
  1031. if self._parser is None:
  1032. raise ValueError("feed() called after end of stream")
  1033. if data:
  1034. try:
  1035. self._parser.feed(data)
  1036. except SyntaxError as exc:
  1037. self._events_queue.append(exc)
  1038. def _close_and_return_root(self):
  1039. # iterparse needs this to set its root attribute properly :(
  1040. root = self._parser.close()
  1041. self._parser = None
  1042. return root
  1043. def close(self):
  1044. """Finish feeding data to parser.
  1045. Unlike XMLParser, does not return the root element. Use
  1046. read_events() to consume elements from XMLPullParser.
  1047. """
  1048. self._close_and_return_root()
  1049. def read_events(self):
  1050. """Return an iterator over currently available (event, elem) pairs.
  1051. Events are consumed from the internal event queue as they are
  1052. retrieved from the iterator.
  1053. """
  1054. events = self._events_queue
  1055. while events:
  1056. event = events.popleft()
  1057. if isinstance(event, Exception):
  1058. raise event
  1059. else:
  1060. yield event
  1061. def flush(self):
  1062. if self._parser is None:
  1063. raise ValueError("flush() called after end of stream")
  1064. self._parser.flush()
  1065. def XML(text, parser=None):
  1066. """Parse XML document from string constant.
  1067. This function can be used to embed "XML Literals" in Python code.
  1068. *text* is a string containing XML data, *parser* is an
  1069. optional parser instance, defaulting to the standard XMLParser.
  1070. Returns an Element instance.
  1071. """
  1072. if not parser:
  1073. parser = XMLParser(target=TreeBuilder())
  1074. parser.feed(text)
  1075. return parser.close()
  1076. def XMLID(text, parser=None):
  1077. """Parse XML document from string constant for its IDs.
  1078. *text* is a string containing XML data, *parser* is an
  1079. optional parser instance, defaulting to the standard XMLParser.
  1080. Returns an (Element, dict) tuple, in which the
  1081. dict maps element id:s to elements.
  1082. """
  1083. if not parser:
  1084. parser = XMLParser(target=TreeBuilder())
  1085. parser.feed(text)
  1086. tree = parser.close()
  1087. ids = {}
  1088. for elem in tree.iter():
  1089. id = elem.get("id")
  1090. if id:
  1091. ids[id] = elem
  1092. return tree, ids
  1093. # Parse XML document from string constant. Alias for XML().
  1094. fromstring = XML
  1095. def fromstringlist(sequence, parser=None):
  1096. """Parse XML document from sequence of string fragments.
  1097. *sequence* is a list of other sequence, *parser* is an optional parser
  1098. instance, defaulting to the standard XMLParser.
  1099. Returns an Element instance.
  1100. """
  1101. if not parser:
  1102. parser = XMLParser(target=TreeBuilder())
  1103. for text in sequence:
  1104. parser.feed(text)
  1105. return parser.close()
  1106. # --------------------------------------------------------------------
  1107. class TreeBuilder:
  1108. """Generic element structure builder.
  1109. This builder converts a sequence of start, data, and end method
  1110. calls to a well-formed element structure.
  1111. You can use this class to build an element structure using a custom XML
  1112. parser, or a parser for some other XML-like format.
  1113. *element_factory* is an optional element factory which is called
  1114. to create new Element instances, as necessary.
  1115. *comment_factory* is a factory to create comments to be used instead of
  1116. the standard factory. If *insert_comments* is false (the default),
  1117. comments will not be inserted into the tree.
  1118. *pi_factory* is a factory to create processing instructions to be used
  1119. instead of the standard factory. If *insert_pis* is false (the default),
  1120. processing instructions will not be inserted into the tree.
  1121. """
  1122. def __init__(self, element_factory=None, *,
  1123. comment_factory=None, pi_factory=None,
  1124. insert_comments=False, insert_pis=False):
  1125. self._data = [] # data collector
  1126. self._elem = [] # element stack
  1127. self._last = None # last element
  1128. self._root = None # root element
  1129. self._tail = None # true if we're after an end tag
  1130. if comment_factory is None:
  1131. comment_factory = Comment
  1132. self._comment_factory = comment_factory
  1133. self.insert_comments = insert_comments
  1134. if pi_factory is None:
  1135. pi_factory = ProcessingInstruction
  1136. self._pi_factory = pi_factory
  1137. self.insert_pis = insert_pis
  1138. if element_factory is None:
  1139. element_factory = Element
  1140. self._factory = element_factory
  1141. def close(self):
  1142. """Flush builder buffers and return toplevel document Element."""
  1143. assert len(self._elem) == 0, "missing end tags"
  1144. assert self._root is not None, "missing toplevel element"
  1145. return self._root
  1146. def _flush(self):
  1147. if self._data:
  1148. if self._last is not None:
  1149. text = "".join(self._data)
  1150. if self._tail:
  1151. assert self._last.tail is None, "internal error (tail)"
  1152. self._last.tail = text
  1153. else:
  1154. assert self._last.text is None, "internal error (text)"
  1155. self._last.text = text
  1156. self._data = []
  1157. def data(self, data):
  1158. """Add text to current element."""
  1159. self._data.append(data)
  1160. def start(self, tag, attrs):
  1161. """Open new element and return it.
  1162. *tag* is the element name, *attrs* is a dict containing element
  1163. attributes.
  1164. """
  1165. self._flush()
  1166. self._last = elem = self._factory(tag, attrs)
  1167. if self._elem:
  1168. self._elem[-1].append(elem)
  1169. elif self._root is None:
  1170. self._root = elem
  1171. self._elem.append(elem)
  1172. self._tail = 0
  1173. return elem
  1174. def end(self, tag):
  1175. """Close and return current Element.
  1176. *tag* is the element name.
  1177. """
  1178. self._flush()
  1179. self._last = self._elem.pop()
  1180. assert self._last.tag == tag,\
  1181. "end tag mismatch (expected %s, got %s)" % (
  1182. self._last.tag, tag)
  1183. self._tail = 1
  1184. return self._last
  1185. def comment(self, text):
  1186. """Create a comment using the comment_factory.
  1187. *text* is the text of the comment.
  1188. """
  1189. return self._handle_single(
  1190. self._comment_factory, self.insert_comments, text)
  1191. def pi(self, target, text=None):
  1192. """Create a processing instruction using the pi_factory.
  1193. *target* is the target name of the processing instruction.
  1194. *text* is the data of the processing instruction, or ''.
  1195. """
  1196. return self._handle_single(
  1197. self._pi_factory, self.insert_pis, target, text)
  1198. def _handle_single(self, factory, insert, *args):
  1199. elem = factory(*args)
  1200. if insert:
  1201. self._flush()
  1202. self._last = elem
  1203. if self._elem:
  1204. self._elem[-1].append(elem)
  1205. self._tail = 1
  1206. return elem
  1207. # also see ElementTree and TreeBuilder
  1208. class XMLParser:
  1209. """Element structure builder for XML source data based on the expat parser.
  1210. *target* is an optional target object which defaults to an instance of the
  1211. standard TreeBuilder class, *encoding* is an optional encoding string
  1212. which if given, overrides the encoding specified in the XML file:
  1213. http://www.iana.org/assignments/character-sets
  1214. """
  1215. def __init__(self, *, target=None, encoding=None):
  1216. try:
  1217. from xml.parsers import expat
  1218. except ImportError:
  1219. try:
  1220. import pyexpat as expat
  1221. except ImportError:
  1222. raise ImportError(
  1223. "No module named expat; use SimpleXMLTreeBuilder instead"
  1224. )
  1225. parser = expat.ParserCreate(encoding, "}")
  1226. if target is None:
  1227. target = TreeBuilder()
  1228. # underscored names are provided for compatibility only
  1229. self.parser = self._parser = parser
  1230. self.target = self._target = target
  1231. self._error = expat.error
  1232. self._names = {} # name memo cache
  1233. # main callbacks
  1234. parser.DefaultHandlerExpand = self._default
  1235. if hasattr(target, 'start'):
  1236. parser.StartElementHandler = self._start
  1237. if hasattr(target, 'end'):
  1238. parser.EndElementHandler = self._end
  1239. if hasattr(target, 'start_ns'):
  1240. parser.StartNamespaceDeclHandler = self._start_ns
  1241. if hasattr(target, 'end_ns'):
  1242. parser.EndNamespaceDeclHandler = self._end_ns
  1243. if hasattr(target, 'data'):
  1244. parser.CharacterDataHandler = target.data
  1245. # miscellaneous callbacks
  1246. if hasattr(target, 'comment'):
  1247. parser.CommentHandler = target.comment
  1248. if hasattr(target, 'pi'):
  1249. parser.ProcessingInstructionHandler = target.pi
  1250. # Configure pyexpat: buffering, new-style attribute handling.
  1251. parser.buffer_text = 1
  1252. parser.ordered_attributes = 1
  1253. self._doctype = None
  1254. self.entity = {}
  1255. try:
  1256. self.version = "Expat %d.%d.%d" % expat.version_info
  1257. except AttributeError:
  1258. pass # unknown
  1259. def _setevents(self, events_queue, events_to_report):
  1260. # Internal API for XMLPullParser
  1261. # events_to_report: a list of events to report during parsing (same as
  1262. # the *events* of XMLPullParser's constructor.
  1263. # events_queue: a list of actual parsing events that will be populated
  1264. # by the underlying parser.
  1265. #
  1266. parser = self._parser
  1267. append = events_queue.append
  1268. for event_name in events_to_report:
  1269. if event_name == "start":
  1270. parser.ordered_attributes = 1
  1271. def handler(tag, attrib_in, event=event_name, append=append,
  1272. start=self._start):
  1273. append((event, start(tag, attrib_in)))
  1274. parser.StartElementHandler = handler
  1275. elif event_name == "end":
  1276. def handler(tag, event=event_name, append=append,
  1277. end=self._end):
  1278. append((event, end(tag)))
  1279. parser.EndElementHandler = handler
  1280. elif event_name == "start-ns":
  1281. # TreeBuilder does not implement .start_ns()
  1282. if hasattr(self.target, "start_ns"):
  1283. def handler(prefix, uri, event=event_name, append=append,
  1284. start_ns=self._start_ns):
  1285. append((event, start_ns(prefix, uri)))
  1286. else:
  1287. def handler(prefix, uri, event=event_name, append=append):
  1288. append((event, (prefix or '', uri or '')))
  1289. parser.StartNamespaceDeclHandler = handler
  1290. elif event_name == "end-ns":
  1291. # TreeBuilder does not implement .end_ns()
  1292. if hasattr(self.target, "end_ns"):
  1293. def handler(prefix, event=event_name, append=append,
  1294. end_ns=self._end_ns):
  1295. append((event, end_ns(prefix)))
  1296. else:
  1297. def handler(prefix, event=event_name, append=append):
  1298. append((event, None))
  1299. parser.EndNamespaceDeclHandler = handler
  1300. elif event_name == 'comment':
  1301. def handler(text, event=event_name, append=append, self=self):
  1302. append((event, self.target.comment(text)))
  1303. parser.CommentHandler = handler
  1304. elif event_name == 'pi':
  1305. def handler(pi_target, data, event=event_name, append=append,
  1306. self=self):
  1307. append((event, self.target.pi(pi_target, data)))
  1308. parser.ProcessingInstructionHandler = handler
  1309. else:
  1310. raise ValueError("unknown event %r" % event_name)
  1311. def _raiseerror(self, value):
  1312. err = ParseError(value)
  1313. err.code = value.code
  1314. err.position = value.lineno, value.offset
  1315. raise err
  1316. def _fixname(self, key):
  1317. # expand qname, and convert name string to ascii, if possible
  1318. try:
  1319. name = self._names[key]
  1320. except KeyError:
  1321. name = key
  1322. if "}" in name:
  1323. name = "{" + name
  1324. self._names[key] = name
  1325. return name
  1326. def _start_ns(self, prefix, uri):
  1327. return self.target.start_ns(prefix or '', uri or '')
  1328. def _end_ns(self, prefix):
  1329. return self.target.end_ns(prefix or '')
  1330. def _start(self, tag, attr_list):
  1331. # Handler for expat's StartElementHandler. Since ordered_attributes
  1332. # is set, the attributes are reported as a list of alternating
  1333. # attribute name,value.
  1334. fixname = self._fixname
  1335. tag = fixname(tag)
  1336. attrib = {}
  1337. if attr_list:
  1338. for i in range(0, len(attr_list), 2):
  1339. attrib[fixname(attr_list[i])] = attr_list[i+1]
  1340. return self.target.start(tag, attrib)
  1341. def _end(self, tag):
  1342. return self.target.end(self._fixname(tag))
  1343. def _default(self, text):
  1344. prefix = text[:1]
  1345. if prefix == "&":
  1346. # deal with undefined entities
  1347. try:
  1348. data_handler = self.target.data
  1349. except AttributeError:
  1350. return
  1351. try:
  1352. data_handler(self.entity[text[1:-1]])
  1353. except KeyError:
  1354. from xml.parsers import expat
  1355. err = expat.error(
  1356. "undefined entity %s: line %d, column %d" %
  1357. (text, self.parser.ErrorLineNumber,
  1358. self.parser.ErrorColumnNumber)
  1359. )
  1360. err.code = 11 # XML_ERROR_UNDEFINED_ENTITY
  1361. err.lineno = self.parser.ErrorLineNumber
  1362. err.offset = self.parser.ErrorColumnNumber
  1363. raise err
  1364. elif prefix == "<" and text[:9] == "<!DOCTYPE":
  1365. self._doctype = [] # inside a doctype declaration
  1366. elif self._doctype is not None:
  1367. # parse doctype contents
  1368. if prefix == ">":
  1369. self._doctype = None
  1370. return
  1371. text = text.strip()
  1372. if not text:
  1373. return
  1374. self._doctype.append(text)
  1375. n = len(self._doctype)
  1376. if n > 2:
  1377. type = self._doctype[1]
  1378. if type == "PUBLIC" and n == 4:
  1379. name, type, pubid, system = self._doctype
  1380. if pubid:
  1381. pubid = pubid[1:-1]
  1382. elif type == "SYSTEM" and n == 3:
  1383. name, type, system = self._doctype
  1384. pubid = None
  1385. else:
  1386. return
  1387. if hasattr(self.target, "doctype"):
  1388. self.target.doctype(name, pubid, system[1:-1])
  1389. elif hasattr(self, "doctype"):
  1390. warnings.warn(
  1391. "The doctype() method of XMLParser is ignored. "
  1392. "Define doctype() method on the TreeBuilder target.",
  1393. RuntimeWarning)
  1394. self._doctype = None
  1395. def feed(self, data):
  1396. """Feed encoded data to parser."""
  1397. try:
  1398. self.parser.Parse(data, False)
  1399. except self._error as v:
  1400. self._raiseerror(v)
  1401. def close(self):
  1402. """Finish feeding data to parser and return element structure."""
  1403. try:
  1404. self.parser.Parse(b"", True) # end of data
  1405. except self._error as v:
  1406. self._raiseerror(v)
  1407. try:
  1408. close_handler = self.target.close
  1409. except AttributeError:
  1410. pass
  1411. else:
  1412. return close_handler()
  1413. finally:
  1414. # get rid of circular references
  1415. del self.parser, self._parser
  1416. del self.target, self._target
  1417. def flush(self):
  1418. was_enabled = self.parser.GetReparseDeferralEnabled()
  1419. try:
  1420. self.parser.SetReparseDeferralEnabled(False)
  1421. self.parser.Parse(b"", False)
  1422. except self._error as v:
  1423. self._raiseerror(v)
  1424. finally:
  1425. self.parser.SetReparseDeferralEnabled(was_enabled)
  1426. # --------------------------------------------------------------------
  1427. # C14N 2.0
  1428. def canonicalize(xml_data=None, *, out=None, from_file=None, **options):
  1429. """Convert XML to its C14N 2.0 serialised form.
  1430. If *out* is provided, it must be a file or file-like object that receives
  1431. the serialised canonical XML output (text, not bytes) through its ``.write()``
  1432. method. To write to a file, open it in text mode with encoding "utf-8".
  1433. If *out* is not provided, this function returns the output as text string.
  1434. Either *xml_data* (an XML string) or *from_file* (a file path or
  1435. file-like object) must be provided as input.
  1436. The configuration options are the same as for the ``C14NWriterTarget``.
  1437. """
  1438. if xml_data is None and from_file is None:
  1439. raise ValueError("Either 'xml_data' or 'from_file' must be provided as input")
  1440. sio = None
  1441. if out is None:
  1442. sio = out = io.StringIO()
  1443. parser = XMLParser(target=C14NWriterTarget(out.write, **options))
  1444. if xml_data is not None:
  1445. parser.feed(xml_data)
  1446. parser.close()
  1447. elif from_file is not None:
  1448. parse(from_file, parser=parser)
  1449. return sio.getvalue() if sio is not None else None
  1450. _looks_like_prefix_name = re.compile(r'^\w+:\w+$', re.UNICODE).match
  1451. class C14NWriterTarget:
  1452. """
  1453. Canonicalization writer target for the XMLParser.
  1454. Serialises parse events to XML C14N 2.0.
  1455. The *write* function is used for writing out the resulting data stream
  1456. as text (not bytes). To write to a file, open it in text mode with encoding
  1457. "utf-8" and pass its ``.write`` method.
  1458. Configuration options:
  1459. - *with_comments*: set to true to include comments
  1460. - *strip_text*: set to true to strip whitespace before and after text content
  1461. - *rewrite_prefixes*: set to true to replace namespace prefixes by "n{number}"
  1462. - *qname_aware_tags*: a set of qname aware tag names in which prefixes
  1463. should be replaced in text content
  1464. - *qname_aware_attrs*: a set of qname aware attribute names in which prefixes
  1465. should be replaced in text content
  1466. - *exclude_attrs*: a set of attribute names that should not be serialised
  1467. - *exclude_tags*: a set of tag names that should not be serialised
  1468. """
  1469. def __init__(self, write, *,
  1470. with_comments=False, strip_text=False, rewrite_prefixes=False,
  1471. qname_aware_tags=None, qname_aware_attrs=None,
  1472. exclude_attrs=None, exclude_tags=None):
  1473. self._write = write
  1474. self._data = []
  1475. self._with_comments = with_comments
  1476. self._strip_text = strip_text
  1477. self._exclude_attrs = set(exclude_attrs) if exclude_attrs else None
  1478. self._exclude_tags = set(exclude_tags) if exclude_tags else None
  1479. self._rewrite_prefixes = rewrite_prefixes
  1480. if qname_aware_tags:
  1481. self._qname_aware_tags = set(qname_aware_tags)
  1482. else:
  1483. self._qname_aware_tags = None
  1484. if qname_aware_attrs:
  1485. self._find_qname_aware_attrs = set(qname_aware_attrs).intersection
  1486. else:
  1487. self._find_qname_aware_attrs = None
  1488. # Stack with globally and newly declared namespaces as (uri, prefix) pairs.
  1489. self._declared_ns_stack = [[
  1490. ("http://www.w3.org/XML/1998/namespace", "xml"),
  1491. ]]
  1492. # Stack with user declared namespace prefixes as (uri, prefix) pairs.
  1493. self._ns_stack = []
  1494. if not rewrite_prefixes:
  1495. self._ns_stack.append(list(_namespace_map.items()))
  1496. self._ns_stack.append([])
  1497. self._prefix_map = {}
  1498. self._preserve_space = [False]
  1499. self._pending_start = None
  1500. self._root_seen = False
  1501. self._root_done = False
  1502. self._ignored_depth = 0
  1503. def _iter_namespaces(self, ns_stack, _reversed=reversed):
  1504. for namespaces in _reversed(ns_stack):
  1505. if namespaces: # almost no element declares new namespaces
  1506. yield from namespaces
  1507. def _resolve_prefix_name(self, prefixed_name):
  1508. prefix, name = prefixed_name.split(':', 1)
  1509. for uri, p in self._iter_namespaces(self._ns_stack):
  1510. if p == prefix:
  1511. return f'{{{uri}}}{name}'
  1512. raise ValueError(f'Prefix {prefix} of QName "{prefixed_name}" is not declared in scope')
  1513. def _qname(self, qname, uri=None):
  1514. if uri is None:
  1515. uri, tag = qname[1:].rsplit('}', 1) if qname[:1] == '{' else ('', qname)
  1516. else:
  1517. tag = qname
  1518. prefixes_seen = set()
  1519. for u, prefix in self._iter_namespaces(self._declared_ns_stack):
  1520. if u == uri and prefix not in prefixes_seen:
  1521. return f'{prefix}:{tag}' if prefix else tag, tag, uri
  1522. prefixes_seen.add(prefix)
  1523. # Not declared yet => add new declaration.
  1524. if self._rewrite_prefixes:
  1525. if uri in self._prefix_map:
  1526. prefix = self._prefix_map[uri]
  1527. else:
  1528. prefix = self._prefix_map[uri] = f'n{len(self._prefix_map)}'
  1529. self._declared_ns_stack[-1].append((uri, prefix))
  1530. return f'{prefix}:{tag}', tag, uri
  1531. if not uri and '' not in prefixes_seen:
  1532. # No default namespace declared => no prefix needed.
  1533. return tag, tag, uri
  1534. for u, prefix in self._iter_namespaces(self._ns_stack):
  1535. if u == uri:
  1536. self._declared_ns_stack[-1].append((uri, prefix))
  1537. return f'{prefix}:{tag}' if prefix else tag, tag, uri
  1538. if not uri:
  1539. # As soon as a default namespace is defined,
  1540. # anything that has no namespace (and thus, no prefix) goes there.
  1541. return tag, tag, uri
  1542. raise ValueError(f'Namespace "{uri}" is not declared in scope')
  1543. def data(self, data):
  1544. if not self._ignored_depth:
  1545. self._data.append(data)
  1546. def _flush(self, _join_text=''.join):
  1547. data = _join_text(self._data)
  1548. del self._data[:]
  1549. if self._strip_text and not self._preserve_space[-1]:
  1550. data = data.strip()
  1551. if self._pending_start is not None:
  1552. args, self._pending_start = self._pending_start, None
  1553. qname_text = data if data and _looks_like_prefix_name(data) else None
  1554. self._start(*args, qname_text)
  1555. if qname_text is not None:
  1556. return
  1557. if data and self._root_seen:
  1558. self._write(_escape_cdata_c14n(data))
  1559. def start_ns(self, prefix, uri):
  1560. if self._ignored_depth:
  1561. return
  1562. # we may have to resolve qnames in text content
  1563. if self._data:
  1564. self._flush()
  1565. self._ns_stack[-1].append((uri, prefix))
  1566. def start(self, tag, attrs):
  1567. if self._exclude_tags is not None and (
  1568. self._ignored_depth or tag in self._exclude_tags):
  1569. self._ignored_depth += 1
  1570. return
  1571. if self._data:
  1572. self._flush()
  1573. new_namespaces = []
  1574. self._declared_ns_stack.append(new_namespaces)
  1575. if self._qname_aware_tags is not None and tag in self._qname_aware_tags:
  1576. # Need to parse text first to see if it requires a prefix declaration.
  1577. self._pending_start = (tag, attrs, new_namespaces)
  1578. return
  1579. self._start(tag, attrs, new_namespaces)
  1580. def _start(self, tag, attrs, new_namespaces, qname_text=None):
  1581. if self._exclude_attrs is not None and attrs:
  1582. attrs = {k: v for k, v in attrs.items() if k not in self._exclude_attrs}
  1583. qnames = {tag, *attrs}
  1584. resolved_names = {}
  1585. # Resolve prefixes in attribute and tag text.
  1586. if qname_text is not None:
  1587. qname = resolved_names[qname_text] = self._resolve_prefix_name(qname_text)
  1588. qnames.add(qname)
  1589. if self._find_qname_aware_attrs is not None and attrs:
  1590. qattrs = self._find_qname_aware_attrs(attrs)
  1591. if qattrs:
  1592. for attr_name in qattrs:
  1593. value = attrs[attr_name]
  1594. if _looks_like_prefix_name(value):
  1595. qname = resolved_names[value] = self._resolve_prefix_name(value)
  1596. qnames.add(qname)
  1597. else:
  1598. qattrs = None
  1599. else:
  1600. qattrs = None
  1601. # Assign prefixes in lexicographical order of used URIs.
  1602. parse_qname = self._qname
  1603. parsed_qnames = {n: parse_qname(n) for n in sorted(
  1604. qnames, key=lambda n: n.split('}', 1))}
  1605. # Write namespace declarations in prefix order ...
  1606. if new_namespaces:
  1607. attr_list = [
  1608. ('xmlns:' + prefix if prefix else 'xmlns', uri)
  1609. for uri, prefix in new_namespaces
  1610. ]
  1611. attr_list.sort()
  1612. else:
  1613. # almost always empty
  1614. attr_list = []
  1615. # ... followed by attributes in URI+name order
  1616. if attrs:
  1617. for k, v in sorted(attrs.items()):
  1618. if qattrs is not None and k in qattrs and v in resolved_names:
  1619. v = parsed_qnames[resolved_names[v]][0]
  1620. attr_qname, attr_name, uri = parsed_qnames[k]
  1621. # No prefix for attributes in default ('') namespace.
  1622. attr_list.append((attr_qname if uri else attr_name, v))
  1623. # Honour xml:space attributes.
  1624. space_behaviour = attrs.get('{http://www.w3.org/XML/1998/namespace}space')
  1625. self._preserve_space.append(
  1626. space_behaviour == 'preserve' if space_behaviour
  1627. else self._preserve_space[-1])
  1628. # Write the tag.
  1629. write = self._write
  1630. write('<' + parsed_qnames[tag][0])
  1631. if attr_list:
  1632. write(''.join([f' {k}="{_escape_attrib_c14n(v)}"' for k, v in attr_list]))
  1633. write('>')
  1634. # Write the resolved qname text content.
  1635. if qname_text is not None:
  1636. write(_escape_cdata_c14n(parsed_qnames[resolved_names[qname_text]][0]))
  1637. self._root_seen = True
  1638. self._ns_stack.append([])
  1639. def end(self, tag):
  1640. if self._ignored_depth:
  1641. self._ignored_depth -= 1
  1642. return
  1643. if self._data:
  1644. self._flush()
  1645. self._write(f'</{self._qname(tag)[0]}>')
  1646. self._preserve_space.pop()
  1647. self._root_done = len(self._preserve_space) == 1
  1648. self._declared_ns_stack.pop()
  1649. self._ns_stack.pop()
  1650. def comment(self, text):
  1651. if not self._with_comments:
  1652. return
  1653. if self._ignored_depth:
  1654. return
  1655. if self._root_done:
  1656. self._write('\n')
  1657. elif self._root_seen and self._data:
  1658. self._flush()
  1659. self._write(f'<!--{_escape_cdata_c14n(text)}-->')
  1660. if not self._root_seen:
  1661. self._write('\n')
  1662. def pi(self, target, data):
  1663. if self._ignored_depth:
  1664. return
  1665. if self._root_done:
  1666. self._write('\n')
  1667. elif self._root_seen and self._data:
  1668. self._flush()
  1669. self._write(
  1670. f'<?{target} {_escape_cdata_c14n(data)}?>' if data else f'<?{target}?>')
  1671. if not self._root_seen:
  1672. self._write('\n')
  1673. def _escape_cdata_c14n(text):
  1674. # escape character data
  1675. try:
  1676. # it's worth avoiding do-nothing calls for strings that are
  1677. # shorter than 500 character, or so. assume that's, by far,
  1678. # the most common case in most applications.
  1679. if '&' in text:
  1680. text = text.replace('&', '&amp;')
  1681. if '<' in text:
  1682. text = text.replace('<', '&lt;')
  1683. if '>' in text:
  1684. text = text.replace('>', '&gt;')
  1685. if '\r' in text:
  1686. text = text.replace('\r', '&#xD;')
  1687. return text
  1688. except (TypeError, AttributeError):
  1689. _raise_serialization_error(text)
  1690. def _escape_attrib_c14n(text):
  1691. # escape attribute value
  1692. try:
  1693. if '&' in text:
  1694. text = text.replace('&', '&amp;')
  1695. if '<' in text:
  1696. text = text.replace('<', '&lt;')
  1697. if '"' in text:
  1698. text = text.replace('"', '&quot;')
  1699. if '\t' in text:
  1700. text = text.replace('\t', '&#x9;')
  1701. if '\n' in text:
  1702. text = text.replace('\n', '&#xA;')
  1703. if '\r' in text:
  1704. text = text.replace('\r', '&#xD;')
  1705. return text
  1706. except (TypeError, AttributeError):
  1707. _raise_serialization_error(text)
  1708. # --------------------------------------------------------------------
  1709. # Import the C accelerators
  1710. try:
  1711. # Element is going to be shadowed by the C implementation. We need to keep
  1712. # the Python version of it accessible for some "creative" by external code
  1713. # (see tests)
  1714. _Element_Py = Element
  1715. # Element, SubElement, ParseError, TreeBuilder, XMLParser, _set_factories
  1716. from _elementtree import *
  1717. from _elementtree import _set_factories
  1718. except ImportError:
  1719. pass
  1720. else:
  1721. _set_factories(Comment, ProcessingInstruction)