PageRenderTime 43ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/xml/etree/ElementTree.py

http://github.com/IronLanguages/main
Python | 1684 lines | 1573 code | 15 blank | 96 comment | 37 complexity | 62a8c608547e6bb28bfae675d7513d6c MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. #
  2. # ElementTree
  3. # $Id: ElementTree.py 3440 2008-07-18 14:45:01Z fredrik $
  4. #
  5. # light-weight XML support for Python 2.3 and later.
  6. #
  7. # history (since 1.2.6):
  8. # 2005-11-12 fl added tostringlist/fromstringlist helpers
  9. # 2006-07-05 fl merged in selected changes from the 1.3 sandbox
  10. # 2006-07-05 fl removed support for 2.1 and earlier
  11. # 2007-06-21 fl added deprecation/future warnings
  12. # 2007-08-25 fl added doctype hook, added parser version attribute etc
  13. # 2007-08-26 fl added new serializer code (better namespace handling, etc)
  14. # 2007-08-27 fl warn for broken /tag searches on tree level
  15. # 2007-09-02 fl added html/text methods to serializer (experimental)
  16. # 2007-09-05 fl added method argument to tostring/tostringlist
  17. # 2007-09-06 fl improved error handling
  18. # 2007-09-13 fl added itertext, iterfind; assorted cleanups
  19. # 2007-12-15 fl added C14N hooks, copy method (experimental)
  20. #
  21. # Copyright (c) 1999-2008 by Fredrik Lundh. All rights reserved.
  22. #
  23. # fredrik@pythonware.com
  24. # http://www.pythonware.com
  25. #
  26. # --------------------------------------------------------------------
  27. # The ElementTree toolkit is
  28. #
  29. # Copyright (c) 1999-2008 by Fredrik Lundh
  30. #
  31. # By obtaining, using, and/or copying this software and/or its
  32. # associated documentation, you agree that you have read, understood,
  33. # and will comply with the following terms and conditions:
  34. #
  35. # Permission to use, copy, modify, and distribute this software and
  36. # its associated documentation for any purpose and without fee is
  37. # hereby granted, provided that the above copyright notice appears in
  38. # all copies, and that both that copyright notice and this permission
  39. # notice appear in supporting documentation, and that the name of
  40. # Secret Labs AB or the author not be used in advertising or publicity
  41. # pertaining to distribution of the software without specific, written
  42. # prior permission.
  43. #
  44. # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  45. # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
  46. # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
  47. # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
  48. # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  49. # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
  50. # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  51. # OF THIS SOFTWARE.
  52. # --------------------------------------------------------------------
  53. # Licensed to PSF under a Contributor Agreement.
  54. # See http://www.python.org/psf/license for licensing details.
  55. __all__ = [
  56. # public symbols
  57. "Comment",
  58. "dump",
  59. "Element", "ElementTree",
  60. "fromstring", "fromstringlist",
  61. "iselement", "iterparse",
  62. "parse", "ParseError",
  63. "PI", "ProcessingInstruction",
  64. "QName",
  65. "SubElement",
  66. "tostring", "tostringlist",
  67. "TreeBuilder",
  68. "VERSION",
  69. "XML",
  70. "XMLParser", "XMLTreeBuilder",
  71. ]
  72. VERSION = "1.3.0"
  73. ##
  74. # The <b>Element</b> type is a flexible container object, designed to
  75. # store hierarchical data structures in memory. The type can be
  76. # described as a cross between a list and a dictionary.
  77. # <p>
  78. # Each element has a number of properties associated with it:
  79. # <ul>
  80. # <li>a <i>tag</i>. This is a string identifying what kind of data
  81. # this element represents (the element type, in other words).</li>
  82. # <li>a number of <i>attributes</i>, stored in a Python dictionary.</li>
  83. # <li>a <i>text</i> string.</li>
  84. # <li>an optional <i>tail</i> string.</li>
  85. # <li>a number of <i>child elements</i>, stored in a Python sequence</li>
  86. # </ul>
  87. #
  88. # To create an element instance, use the {@link #Element} constructor
  89. # or the {@link #SubElement} factory function.
  90. # <p>
  91. # The {@link #ElementTree} class can be used to wrap an element
  92. # structure, and convert it from and to XML.
  93. ##
  94. import sys
  95. import re
  96. import warnings
  97. class _SimpleElementPath(object):
  98. # emulate pre-1.2 find/findtext/findall behaviour
  99. def find(self, element, tag, namespaces=None):
  100. for elem in element:
  101. if elem.tag == tag:
  102. return elem
  103. return None
  104. def findtext(self, element, tag, default=None, namespaces=None):
  105. elem = self.find(element, tag)
  106. if elem is None:
  107. return default
  108. return elem.text or ""
  109. def iterfind(self, element, tag, namespaces=None):
  110. if tag[:3] == ".//":
  111. for elem in element.iter(tag[3:]):
  112. yield elem
  113. for elem in element:
  114. if elem.tag == tag:
  115. yield elem
  116. def findall(self, element, tag, namespaces=None):
  117. return list(self.iterfind(element, tag, namespaces))
  118. try:
  119. from . import ElementPath
  120. except ImportError:
  121. ElementPath = _SimpleElementPath()
  122. ##
  123. # Parser error. This is a subclass of <b>SyntaxError</b>.
  124. # <p>
  125. # In addition to the exception value, an exception instance contains a
  126. # specific exception code in the <b>code</b> attribute, and the line and
  127. # column of the error in the <b>position</b> attribute.
  128. class ParseError(SyntaxError):
  129. pass
  130. # --------------------------------------------------------------------
  131. ##
  132. # Checks if an object appears to be a valid element object.
  133. #
  134. # @param An element instance.
  135. # @return A true value if this is an element object.
  136. # @defreturn flag
  137. def iselement(element):
  138. # FIXME: not sure about this; might be a better idea to look
  139. # for tag/attrib/text attributes
  140. return isinstance(element, Element) or hasattr(element, "tag")
  141. ##
  142. # Element class. This class defines the Element interface, and
  143. # provides a reference implementation of this interface.
  144. # <p>
  145. # The element name, attribute names, and attribute values can be
  146. # either ASCII strings (ordinary Python strings containing only 7-bit
  147. # ASCII characters) or Unicode strings.
  148. #
  149. # @param tag The element name.
  150. # @param attrib An optional dictionary, containing element attributes.
  151. # @param **extra Additional attributes, given as keyword arguments.
  152. # @see Element
  153. # @see SubElement
  154. # @see Comment
  155. # @see ProcessingInstruction
  156. class Element(object):
  157. # <tag attrib>text<child/>...</tag>tail
  158. ##
  159. # (Attribute) Element tag.
  160. tag = None
  161. ##
  162. # (Attribute) Element attribute dictionary. Where possible, use
  163. # {@link #Element.get},
  164. # {@link #Element.set},
  165. # {@link #Element.keys}, and
  166. # {@link #Element.items} to access
  167. # element attributes.
  168. attrib = None
  169. ##
  170. # (Attribute) Text before first subelement. This is either a
  171. # string or the value None. Note that if there was no text, this
  172. # attribute may be either None or an empty string, depending on
  173. # the parser.
  174. text = None
  175. ##
  176. # (Attribute) Text after this element's end tag, but before the
  177. # next sibling element's start tag. This is either a string or
  178. # the value None. Note that if there was no text, this attribute
  179. # may be either None or an empty string, depending on the parser.
  180. tail = None # text after end tag, if any
  181. # constructor
  182. def __init__(self, tag, attrib={}, **extra):
  183. attrib = attrib.copy()
  184. attrib.update(extra)
  185. self.tag = tag
  186. self.attrib = attrib
  187. self._children = []
  188. def __repr__(self):
  189. return "<Element %s at 0x%x>" % (repr(self.tag), id(self))
  190. ##
  191. # Creates a new element object of the same type as this element.
  192. #
  193. # @param tag Element tag.
  194. # @param attrib Element attributes, given as a dictionary.
  195. # @return A new element instance.
  196. def makeelement(self, tag, attrib):
  197. return self.__class__(tag, attrib)
  198. ##
  199. # (Experimental) Copies the current element. This creates a
  200. # shallow copy; subelements will be shared with the original tree.
  201. #
  202. # @return A new element instance.
  203. def copy(self):
  204. elem = self.makeelement(self.tag, self.attrib)
  205. elem.text = self.text
  206. elem.tail = self.tail
  207. elem[:] = self
  208. return elem
  209. ##
  210. # Returns the number of subelements. Note that this only counts
  211. # full elements; to check if there's any content in an element, you
  212. # have to check both the length and the <b>text</b> attribute.
  213. #
  214. # @return The number of subelements.
  215. def __len__(self):
  216. return len(self._children)
  217. def __nonzero__(self):
  218. warnings.warn(
  219. "The behavior of this method will change in future versions. "
  220. "Use specific 'len(elem)' or 'elem is not None' test instead.",
  221. FutureWarning, stacklevel=2
  222. )
  223. return len(self._children) != 0 # emulate old behaviour, for now
  224. ##
  225. # Returns the given subelement, by index.
  226. #
  227. # @param index What subelement to return.
  228. # @return The given subelement.
  229. # @exception IndexError If the given element does not exist.
  230. def __getitem__(self, index):
  231. return self._children[index]
  232. ##
  233. # Replaces the given subelement, by index.
  234. #
  235. # @param index What subelement to replace.
  236. # @param element The new element value.
  237. # @exception IndexError If the given element does not exist.
  238. def __setitem__(self, index, element):
  239. # if isinstance(index, slice):
  240. # for elt in element:
  241. # assert iselement(elt)
  242. # else:
  243. # assert iselement(element)
  244. self._children[index] = element
  245. ##
  246. # Deletes the given subelement, by index.
  247. #
  248. # @param index What subelement to delete.
  249. # @exception IndexError If the given element does not exist.
  250. def __delitem__(self, index):
  251. del self._children[index]
  252. ##
  253. # Adds a subelement to the end of this element. In document order,
  254. # the new element will appear after the last existing subelement (or
  255. # directly after the text, if it's the first subelement), but before
  256. # the end tag for this element.
  257. #
  258. # @param element The element to add.
  259. def append(self, element):
  260. # assert iselement(element)
  261. self._children.append(element)
  262. ##
  263. # Appends subelements from a sequence.
  264. #
  265. # @param elements A sequence object with zero or more elements.
  266. # @since 1.3
  267. def extend(self, elements):
  268. # for element in elements:
  269. # assert iselement(element)
  270. self._children.extend(elements)
  271. ##
  272. # Inserts a subelement at the given position in this element.
  273. #
  274. # @param index Where to insert the new subelement.
  275. def insert(self, index, element):
  276. # assert iselement(element)
  277. self._children.insert(index, element)
  278. ##
  279. # Removes a matching subelement. Unlike the <b>find</b> methods,
  280. # this method compares elements based on identity, not on tag
  281. # value or contents. To remove subelements by other means, the
  282. # easiest way is often to use a list comprehension to select what
  283. # elements to keep, and use slice assignment to update the parent
  284. # element.
  285. #
  286. # @param element What element to remove.
  287. # @exception ValueError If a matching element could not be found.
  288. def remove(self, element):
  289. # assert iselement(element)
  290. self._children.remove(element)
  291. ##
  292. # (Deprecated) Returns all subelements. The elements are returned
  293. # in document order.
  294. #
  295. # @return A list of subelements.
  296. # @defreturn list of Element instances
  297. def getchildren(self):
  298. warnings.warn(
  299. "This method will be removed in future versions. "
  300. "Use 'list(elem)' or iteration over elem instead.",
  301. DeprecationWarning, stacklevel=2
  302. )
  303. return self._children
  304. ##
  305. # Finds the first matching subelement, by tag name or path.
  306. #
  307. # @param path What element to look for.
  308. # @keyparam namespaces Optional namespace prefix map.
  309. # @return The first matching element, or None if no element was found.
  310. # @defreturn Element or None
  311. def find(self, path, namespaces=None):
  312. return ElementPath.find(self, path, namespaces)
  313. ##
  314. # Finds text for the first matching subelement, by tag name or path.
  315. #
  316. # @param path What element to look for.
  317. # @param default What to return if the element was not found.
  318. # @keyparam namespaces Optional namespace prefix map.
  319. # @return The text content of the first matching element, or the
  320. # default value no element was found. Note that if the element
  321. # is found, but has no text content, this method returns an
  322. # empty string.
  323. # @defreturn string
  324. def findtext(self, path, default=None, namespaces=None):
  325. return ElementPath.findtext(self, path, default, namespaces)
  326. ##
  327. # Finds all matching subelements, by tag name or path.
  328. #
  329. # @param path What element to look for.
  330. # @keyparam namespaces Optional namespace prefix map.
  331. # @return A list or other sequence containing all matching elements,
  332. # in document order.
  333. # @defreturn list of Element instances
  334. def findall(self, path, namespaces=None):
  335. return ElementPath.findall(self, path, namespaces)
  336. ##
  337. # Finds all matching subelements, by tag name or path.
  338. #
  339. # @param path What element to look for.
  340. # @keyparam namespaces Optional namespace prefix map.
  341. # @return An iterator or sequence containing all matching elements,
  342. # in document order.
  343. # @defreturn a generated sequence of Element instances
  344. def iterfind(self, path, namespaces=None):
  345. return ElementPath.iterfind(self, path, namespaces)
  346. ##
  347. # Resets an element. This function removes all subelements, clears
  348. # all attributes, and sets the <b>text</b> and <b>tail</b> attributes
  349. # to None.
  350. def clear(self):
  351. self.attrib.clear()
  352. self._children = []
  353. self.text = self.tail = None
  354. ##
  355. # Gets an element attribute. Equivalent to <b>attrib.get</b>, but
  356. # some implementations may handle this a bit more efficiently.
  357. #
  358. # @param key What attribute to look for.
  359. # @param default What to return if the attribute was not found.
  360. # @return The attribute value, or the default value, if the
  361. # attribute was not found.
  362. # @defreturn string or None
  363. def get(self, key, default=None):
  364. return self.attrib.get(key, default)
  365. ##
  366. # Sets an element attribute. Equivalent to <b>attrib[key] = value</b>,
  367. # but some implementations may handle this a bit more efficiently.
  368. #
  369. # @param key What attribute to set.
  370. # @param value The attribute value.
  371. def set(self, key, value):
  372. self.attrib[key] = value
  373. ##
  374. # Gets a list of attribute names. The names are returned in an
  375. # arbitrary order (just like for an ordinary Python dictionary).
  376. # Equivalent to <b>attrib.keys()</b>.
  377. #
  378. # @return A list of element attribute names.
  379. # @defreturn list of strings
  380. def keys(self):
  381. return self.attrib.keys()
  382. ##
  383. # Gets element attributes, as a sequence. The attributes are
  384. # returned in an arbitrary order. Equivalent to <b>attrib.items()</b>.
  385. #
  386. # @return A list of (name, value) tuples for all attributes.
  387. # @defreturn list of (string, string) tuples
  388. def items(self):
  389. return self.attrib.items()
  390. ##
  391. # Creates a tree iterator. The iterator loops over this element
  392. # and all subelements, in document order, and returns all elements
  393. # with a matching tag.
  394. # <p>
  395. # If the tree structure is modified during iteration, new or removed
  396. # elements may or may not be included. To get a stable set, use the
  397. # list() function on the iterator, and loop over the resulting list.
  398. #
  399. # @param tag What tags to look for (default is to return all elements).
  400. # @return An iterator containing all the matching elements.
  401. # @defreturn iterator
  402. def iter(self, tag=None):
  403. if tag == "*":
  404. tag = None
  405. if tag is None or self.tag == tag:
  406. yield self
  407. for e in self._children:
  408. for e in e.iter(tag):
  409. yield e
  410. # compatibility
  411. def getiterator(self, tag=None):
  412. # Change for a DeprecationWarning in 1.4
  413. warnings.warn(
  414. "This method will be removed in future versions. "
  415. "Use 'elem.iter()' or 'list(elem.iter())' instead.",
  416. PendingDeprecationWarning, stacklevel=2
  417. )
  418. return list(self.iter(tag))
  419. ##
  420. # Creates a text iterator. The iterator loops over this element
  421. # and all subelements, in document order, and returns all inner
  422. # text.
  423. #
  424. # @return An iterator containing all inner text.
  425. # @defreturn iterator
  426. def itertext(self):
  427. tag = self.tag
  428. if not isinstance(tag, basestring) and tag is not None:
  429. return
  430. if self.text:
  431. yield self.text
  432. for e in self:
  433. for s in e.itertext():
  434. yield s
  435. if e.tail:
  436. yield e.tail
  437. # compatibility
  438. _Element = _ElementInterface = Element
  439. ##
  440. # Subelement factory. This function creates an element instance, and
  441. # appends it to an existing element.
  442. # <p>
  443. # The element name, attribute names, and attribute values can be
  444. # either 8-bit ASCII strings or Unicode strings.
  445. #
  446. # @param parent The parent element.
  447. # @param tag The subelement name.
  448. # @param attrib An optional dictionary, containing element attributes.
  449. # @param **extra Additional attributes, given as keyword arguments.
  450. # @return An element instance.
  451. # @defreturn Element
  452. def SubElement(parent, tag, attrib={}, **extra):
  453. attrib = attrib.copy()
  454. attrib.update(extra)
  455. element = parent.makeelement(tag, attrib)
  456. parent.append(element)
  457. return element
  458. ##
  459. # Comment element factory. This factory function creates a special
  460. # element that will be serialized as an XML comment by the standard
  461. # serializer.
  462. # <p>
  463. # The comment string can be either an 8-bit ASCII string or a Unicode
  464. # string.
  465. #
  466. # @param text A string containing the comment string.
  467. # @return An element instance, representing a comment.
  468. # @defreturn Element
  469. def Comment(text=None):
  470. element = Element(Comment)
  471. element.text = text
  472. return element
  473. ##
  474. # PI element factory. This factory function creates a special element
  475. # that will be serialized as an XML processing instruction by the standard
  476. # serializer.
  477. #
  478. # @param target A string containing the PI target.
  479. # @param text A string containing the PI contents, if any.
  480. # @return An element instance, representing a PI.
  481. # @defreturn Element
  482. def ProcessingInstruction(target, text=None):
  483. element = Element(ProcessingInstruction)
  484. element.text = target
  485. if text:
  486. element.text = element.text + " " + text
  487. return element
  488. PI = ProcessingInstruction
  489. ##
  490. # QName wrapper. This can be used to wrap a QName attribute value, in
  491. # order to get proper namespace handling on output.
  492. #
  493. # @param text A string containing the QName value, in the form {uri}local,
  494. # or, if the tag argument is given, the URI part of a QName.
  495. # @param tag Optional tag. If given, the first argument is interpreted as
  496. # a URI, and this argument is interpreted as a local name.
  497. # @return An opaque object, representing the QName.
  498. class QName(object):
  499. def __init__(self, text_or_uri, tag=None):
  500. if tag:
  501. text_or_uri = "{%s}%s" % (text_or_uri, tag)
  502. self.text = text_or_uri
  503. def __str__(self):
  504. return self.text
  505. def __hash__(self):
  506. return hash(self.text)
  507. def __cmp__(self, other):
  508. if isinstance(other, QName):
  509. return cmp(self.text, other.text)
  510. return cmp(self.text, other)
  511. # --------------------------------------------------------------------
  512. ##
  513. # ElementTree wrapper class. This class represents an entire element
  514. # hierarchy, and adds some extra support for serialization to and from
  515. # standard XML.
  516. #
  517. # @param element Optional root element.
  518. # @keyparam file Optional file handle or file name. If given, the
  519. # tree is initialized with the contents of this XML file.
  520. class ElementTree(object):
  521. def __init__(self, element=None, file=None):
  522. # assert element is None or iselement(element)
  523. self._root = element # first node
  524. if file:
  525. self.parse(file)
  526. ##
  527. # Gets the root element for this tree.
  528. #
  529. # @return An element instance.
  530. # @defreturn Element
  531. def getroot(self):
  532. return self._root
  533. ##
  534. # Replaces the root element for this tree. This discards the
  535. # current contents of the tree, and replaces it with the given
  536. # element. Use with care.
  537. #
  538. # @param element An element instance.
  539. def _setroot(self, element):
  540. # assert iselement(element)
  541. self._root = element
  542. ##
  543. # Loads an external XML document into this element tree.
  544. #
  545. # @param source A file name or file object. If a file object is
  546. # given, it only has to implement a <b>read(n)</b> method.
  547. # @keyparam parser An optional parser instance. If not given, the
  548. # standard {@link XMLParser} parser is used.
  549. # @return The document root element.
  550. # @defreturn Element
  551. # @exception ParseError If the parser fails to parse the document.
  552. def parse(self, source, parser=None):
  553. close_source = False
  554. if not hasattr(source, "read"):
  555. source = open(source, "rb")
  556. close_source = True
  557. try:
  558. if not parser:
  559. parser = XMLParser(target=TreeBuilder())
  560. while 1:
  561. data = source.read(65536)
  562. if not data:
  563. break
  564. parser.feed(data)
  565. self._root = parser.close()
  566. return self._root
  567. finally:
  568. if close_source:
  569. source.close()
  570. ##
  571. # Creates a tree iterator for the root element. The iterator loops
  572. # over all elements in this tree, in document order.
  573. #
  574. # @param tag What tags to look for (default is to return all elements)
  575. # @return An iterator.
  576. # @defreturn iterator
  577. def iter(self, tag=None):
  578. # assert self._root is not None
  579. return self._root.iter(tag)
  580. # compatibility
  581. def getiterator(self, tag=None):
  582. # Change for a DeprecationWarning in 1.4
  583. warnings.warn(
  584. "This method will be removed in future versions. "
  585. "Use 'tree.iter()' or 'list(tree.iter())' instead.",
  586. PendingDeprecationWarning, stacklevel=2
  587. )
  588. return list(self.iter(tag))
  589. ##
  590. # Same as getroot().find(path), starting at the root of the
  591. # tree.
  592. #
  593. # @param path What element to look for.
  594. # @keyparam namespaces Optional namespace prefix map.
  595. # @return The first matching element, or None if no element was found.
  596. # @defreturn Element or None
  597. def find(self, path, namespaces=None):
  598. # assert self._root is not None
  599. if path[:1] == "/":
  600. path = "." + path
  601. warnings.warn(
  602. "This search is broken in 1.3 and earlier, and will be "
  603. "fixed in a future version. If you rely on the current "
  604. "behaviour, change it to %r" % path,
  605. FutureWarning, stacklevel=2
  606. )
  607. return self._root.find(path, namespaces)
  608. ##
  609. # Same as getroot().findtext(path), starting at the root of the tree.
  610. #
  611. # @param path What element to look for.
  612. # @param default What to return if the element was not found.
  613. # @keyparam namespaces Optional namespace prefix map.
  614. # @return The text content of the first matching element, or the
  615. # default value no element was found. Note that if the element
  616. # is found, but has no text content, this method returns an
  617. # empty string.
  618. # @defreturn string
  619. def findtext(self, path, default=None, namespaces=None):
  620. # assert self._root is not None
  621. if path[:1] == "/":
  622. path = "." + path
  623. warnings.warn(
  624. "This search is broken in 1.3 and earlier, and will be "
  625. "fixed in a future version. If you rely on the current "
  626. "behaviour, change it to %r" % path,
  627. FutureWarning, stacklevel=2
  628. )
  629. return self._root.findtext(path, default, namespaces)
  630. ##
  631. # Same as getroot().findall(path), starting at the root of the tree.
  632. #
  633. # @param path What element to look for.
  634. # @keyparam namespaces Optional namespace prefix map.
  635. # @return A list or iterator containing all matching elements,
  636. # in document order.
  637. # @defreturn list of Element instances
  638. def findall(self, path, namespaces=None):
  639. # assert self._root is not None
  640. if path[:1] == "/":
  641. path = "." + path
  642. warnings.warn(
  643. "This search is broken in 1.3 and earlier, and will be "
  644. "fixed in a future version. If you rely on the current "
  645. "behaviour, change it to %r" % path,
  646. FutureWarning, stacklevel=2
  647. )
  648. return self._root.findall(path, namespaces)
  649. ##
  650. # Finds all matching subelements, by tag name or path.
  651. # Same as getroot().iterfind(path).
  652. #
  653. # @param path What element to look for.
  654. # @keyparam namespaces Optional namespace prefix map.
  655. # @return An iterator or sequence containing all matching elements,
  656. # in document order.
  657. # @defreturn a generated sequence of Element instances
  658. def iterfind(self, path, namespaces=None):
  659. # assert self._root is not None
  660. if path[:1] == "/":
  661. path = "." + path
  662. warnings.warn(
  663. "This search is broken in 1.3 and earlier, and will be "
  664. "fixed in a future version. If you rely on the current "
  665. "behaviour, change it to %r" % path,
  666. FutureWarning, stacklevel=2
  667. )
  668. return self._root.iterfind(path, namespaces)
  669. ##
  670. # Writes the element tree to a file, as XML.
  671. #
  672. # @def write(file, **options)
  673. # @param file A file name, or a file object opened for writing.
  674. # @param **options Options, given as keyword arguments.
  675. # @keyparam encoding Optional output encoding (default is US-ASCII).
  676. # @keyparam xml_declaration Controls if an XML declaration should
  677. # be added to the file. Use False for never, True for always,
  678. # None for only if not US-ASCII or UTF-8. None is default.
  679. # @keyparam default_namespace Sets the default XML namespace (for "xmlns").
  680. # @keyparam method Optional output method ("xml", "html", "text" or
  681. # "c14n"; default is "xml").
  682. def write(self, file_or_filename,
  683. # keyword arguments
  684. encoding=None,
  685. xml_declaration=None,
  686. default_namespace=None,
  687. method=None):
  688. # assert self._root is not None
  689. if not method:
  690. method = "xml"
  691. elif method not in _serialize:
  692. # FIXME: raise an ImportError for c14n if ElementC14N is missing?
  693. raise ValueError("unknown method %r" % method)
  694. if hasattr(file_or_filename, "write"):
  695. file = file_or_filename
  696. else:
  697. file = open(file_or_filename, "wb")
  698. write = file.write
  699. if not encoding:
  700. if method == "c14n":
  701. encoding = "utf-8"
  702. else:
  703. encoding = "us-ascii"
  704. elif xml_declaration or (xml_declaration is None and
  705. encoding not in ("utf-8", "us-ascii")):
  706. if method == "xml":
  707. write("<?xml version='1.0' encoding='%s'?>\n" % encoding)
  708. if method == "text":
  709. _serialize_text(write, self._root, encoding)
  710. else:
  711. qnames, namespaces = _namespaces(
  712. self._root, encoding, default_namespace
  713. )
  714. serialize = _serialize[method]
  715. serialize(write, self._root, encoding, qnames, namespaces)
  716. if file_or_filename is not file:
  717. file.close()
  718. def write_c14n(self, file):
  719. # lxml.etree compatibility. use output method instead
  720. return self.write(file, method="c14n")
  721. # --------------------------------------------------------------------
  722. # serialization support
  723. def _namespaces(elem, encoding, default_namespace=None):
  724. # identify namespaces used in this tree
  725. # maps qnames to *encoded* prefix:local names
  726. qnames = {None: None}
  727. # maps uri:s to prefixes
  728. namespaces = {}
  729. if default_namespace:
  730. namespaces[default_namespace] = ""
  731. def encode(text):
  732. return text.encode(encoding)
  733. def add_qname(qname):
  734. # calculate serialized qname representation
  735. try:
  736. if qname[:1] == "{":
  737. uri, tag = qname[1:].rsplit("}", 1)
  738. prefix = namespaces.get(uri)
  739. if prefix is None:
  740. prefix = _namespace_map.get(uri)
  741. if prefix is None:
  742. prefix = "ns%d" % len(namespaces)
  743. if prefix != "xml":
  744. namespaces[uri] = prefix
  745. if prefix:
  746. qnames[qname] = encode("%s:%s" % (prefix, tag))
  747. else:
  748. qnames[qname] = encode(tag) # default element
  749. else:
  750. if default_namespace:
  751. # FIXME: can this be handled in XML 1.0?
  752. raise ValueError(
  753. "cannot use non-qualified names with "
  754. "default_namespace option"
  755. )
  756. qnames[qname] = encode(qname)
  757. except TypeError:
  758. _raise_serialization_error(qname)
  759. # populate qname and namespaces table
  760. try:
  761. iterate = elem.iter
  762. except AttributeError:
  763. iterate = elem.getiterator # cET compatibility
  764. for elem in iterate():
  765. tag = elem.tag
  766. if isinstance(tag, QName):
  767. if tag.text not in qnames:
  768. add_qname(tag.text)
  769. elif isinstance(tag, basestring):
  770. if tag not in qnames:
  771. add_qname(tag)
  772. elif tag is not None and tag is not Comment and tag is not PI:
  773. _raise_serialization_error(tag)
  774. for key, value in elem.items():
  775. if isinstance(key, QName):
  776. key = key.text
  777. if key not in qnames:
  778. add_qname(key)
  779. if isinstance(value, QName) and value.text not in qnames:
  780. add_qname(value.text)
  781. text = elem.text
  782. if isinstance(text, QName) and text.text not in qnames:
  783. add_qname(text.text)
  784. return qnames, namespaces
  785. def _serialize_xml(write, elem, encoding, qnames, namespaces):
  786. tag = elem.tag
  787. text = elem.text
  788. if tag is Comment:
  789. write("<!--%s-->" % _encode(text, encoding))
  790. elif tag is ProcessingInstruction:
  791. write("<?%s?>" % _encode(text, encoding))
  792. else:
  793. tag = qnames[tag]
  794. if tag is None:
  795. if text:
  796. write(_escape_cdata(text, encoding))
  797. for e in elem:
  798. _serialize_xml(write, e, encoding, qnames, None)
  799. else:
  800. write("<" + tag)
  801. items = elem.items()
  802. if items or namespaces:
  803. if namespaces:
  804. for v, k in sorted(namespaces.items(),
  805. key=lambda x: x[1]): # sort on prefix
  806. if k:
  807. k = ":" + k
  808. write(" xmlns%s=\"%s\"" % (
  809. k.encode(encoding),
  810. _escape_attrib(v, encoding)
  811. ))
  812. for k, v in sorted(items): # lexical order
  813. if isinstance(k, QName):
  814. k = k.text
  815. if isinstance(v, QName):
  816. v = qnames[v.text]
  817. else:
  818. v = _escape_attrib(v, encoding)
  819. write(" %s=\"%s\"" % (qnames[k], v))
  820. if text or len(elem):
  821. write(">")
  822. if text:
  823. write(_escape_cdata(text, encoding))
  824. for e in elem:
  825. _serialize_xml(write, e, encoding, qnames, None)
  826. write("</" + tag + ">")
  827. else:
  828. write(" />")
  829. if elem.tail:
  830. write(_escape_cdata(elem.tail, encoding))
  831. HTML_EMPTY = ("area", "base", "basefont", "br", "col", "frame", "hr",
  832. "img", "input", "isindex", "link", "meta", "param")
  833. try:
  834. HTML_EMPTY = set(HTML_EMPTY)
  835. except NameError:
  836. pass
  837. def _serialize_html(write, elem, encoding, qnames, namespaces):
  838. tag = elem.tag
  839. text = elem.text
  840. if tag is Comment:
  841. write("<!--%s-->" % _escape_cdata(text, encoding))
  842. elif tag is ProcessingInstruction:
  843. write("<?%s?>" % _escape_cdata(text, encoding))
  844. else:
  845. tag = qnames[tag]
  846. if tag is None:
  847. if text:
  848. write(_escape_cdata(text, encoding))
  849. for e in elem:
  850. _serialize_html(write, e, encoding, qnames, None)
  851. else:
  852. write("<" + tag)
  853. items = elem.items()
  854. if items or namespaces:
  855. if namespaces:
  856. for v, k in sorted(namespaces.items(),
  857. key=lambda x: x[1]): # sort on prefix
  858. if k:
  859. k = ":" + k
  860. write(" xmlns%s=\"%s\"" % (
  861. k.encode(encoding),
  862. _escape_attrib(v, encoding)
  863. ))
  864. for k, v in sorted(items): # lexical order
  865. if isinstance(k, QName):
  866. k = k.text
  867. if isinstance(v, QName):
  868. v = qnames[v.text]
  869. else:
  870. v = _escape_attrib_html(v, encoding)
  871. # FIXME: handle boolean attributes
  872. write(" %s=\"%s\"" % (qnames[k], v))
  873. write(">")
  874. ltag = tag.lower()
  875. if text:
  876. if ltag == "script" or ltag == "style":
  877. write(_encode(text, encoding))
  878. else:
  879. write(_escape_cdata(text, encoding))
  880. for e in elem:
  881. _serialize_html(write, e, encoding, qnames, None)
  882. if ltag not in HTML_EMPTY:
  883. write("</" + tag + ">")
  884. if elem.tail:
  885. write(_escape_cdata(elem.tail, encoding))
  886. def _serialize_text(write, elem, encoding):
  887. for part in elem.itertext():
  888. write(part.encode(encoding))
  889. if elem.tail:
  890. write(elem.tail.encode(encoding))
  891. _serialize = {
  892. "xml": _serialize_xml,
  893. "html": _serialize_html,
  894. "text": _serialize_text,
  895. # this optional method is imported at the end of the module
  896. # "c14n": _serialize_c14n,
  897. }
  898. ##
  899. # Registers a namespace prefix. The registry is global, and any
  900. # existing mapping for either the given prefix or the namespace URI
  901. # will be removed.
  902. #
  903. # @param prefix Namespace prefix.
  904. # @param uri Namespace uri. Tags and attributes in this namespace
  905. # will be serialized with the given prefix, if at all possible.
  906. # @exception ValueError If the prefix is reserved, or is otherwise
  907. # invalid.
  908. def register_namespace(prefix, uri):
  909. if re.match("ns\d+$", prefix):
  910. raise ValueError("Prefix format reserved for internal use")
  911. for k, v in _namespace_map.items():
  912. if k == uri or v == prefix:
  913. del _namespace_map[k]
  914. _namespace_map[uri] = prefix
  915. _namespace_map = {
  916. # "well-known" namespace prefixes
  917. "http://www.w3.org/XML/1998/namespace": "xml",
  918. "http://www.w3.org/1999/xhtml": "html",
  919. "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
  920. "http://schemas.xmlsoap.org/wsdl/": "wsdl",
  921. # xml schema
  922. "http://www.w3.org/2001/XMLSchema": "xs",
  923. "http://www.w3.org/2001/XMLSchema-instance": "xsi",
  924. # dublin core
  925. "http://purl.org/dc/elements/1.1/": "dc",
  926. }
  927. def _raise_serialization_error(text):
  928. raise TypeError(
  929. "cannot serialize %r (type %s)" % (text, type(text).__name__)
  930. )
  931. def _encode(text, encoding):
  932. try:
  933. return text.encode(encoding, "xmlcharrefreplace")
  934. except (TypeError, AttributeError):
  935. _raise_serialization_error(text)
  936. def _escape_cdata(text, encoding):
  937. # escape character data
  938. try:
  939. # it's worth avoiding do-nothing calls for strings that are
  940. # shorter than 500 character, or so. assume that's, by far,
  941. # the most common case in most applications.
  942. if "&" in text:
  943. text = text.replace("&", "&amp;")
  944. if "<" in text:
  945. text = text.replace("<", "&lt;")
  946. if ">" in text:
  947. text = text.replace(">", "&gt;")
  948. return text.encode(encoding, "xmlcharrefreplace")
  949. except (TypeError, AttributeError):
  950. _raise_serialization_error(text)
  951. def _escape_attrib(text, encoding):
  952. # escape attribute value
  953. try:
  954. if "&" in text:
  955. text = text.replace("&", "&amp;")
  956. if "<" in text:
  957. text = text.replace("<", "&lt;")
  958. if ">" in text:
  959. text = text.replace(">", "&gt;")
  960. if "\"" in text:
  961. text = text.replace("\"", "&quot;")
  962. if "\n" in text:
  963. text = text.replace("\n", "&#10;")
  964. return text.encode(encoding, "xmlcharrefreplace")
  965. except (TypeError, AttributeError):
  966. _raise_serialization_error(text)
  967. def _escape_attrib_html(text, encoding):
  968. # escape attribute value
  969. try:
  970. if "&" in text:
  971. text = text.replace("&", "&amp;")
  972. if ">" in text:
  973. text = text.replace(">", "&gt;")
  974. if "\"" in text:
  975. text = text.replace("\"", "&quot;")
  976. return text.encode(encoding, "xmlcharrefreplace")
  977. except (TypeError, AttributeError):
  978. _raise_serialization_error(text)
  979. # --------------------------------------------------------------------
  980. ##
  981. # Generates a string representation of an XML element, including all
  982. # subelements.
  983. #
  984. # @param element An Element instance.
  985. # @keyparam encoding Optional output encoding (default is US-ASCII).
  986. # @keyparam method Optional output method ("xml", "html", "text" or
  987. # "c14n"; default is "xml").
  988. # @return An encoded string containing the XML data.
  989. # @defreturn string
  990. def tostring(element, encoding=None, method=None):
  991. class dummy:
  992. pass
  993. data = []
  994. file = dummy()
  995. file.write = data.append
  996. ElementTree(element).write(file, encoding, method=method)
  997. return "".join(data)
  998. ##
  999. # Generates a string representation of an XML element, including all
  1000. # subelements. The string is returned as a sequence of string fragments.
  1001. #
  1002. # @param element An Element instance.
  1003. # @keyparam encoding Optional output encoding (default is US-ASCII).
  1004. # @keyparam method Optional output method ("xml", "html", "text" or
  1005. # "c14n"; default is "xml").
  1006. # @return A sequence object containing the XML data.
  1007. # @defreturn sequence
  1008. # @since 1.3
  1009. def tostringlist(element, encoding=None, method=None):
  1010. class dummy:
  1011. pass
  1012. data = []
  1013. file = dummy()
  1014. file.write = data.append
  1015. ElementTree(element).write(file, encoding, method=method)
  1016. # FIXME: merge small fragments into larger parts
  1017. return data
  1018. ##
  1019. # Writes an element tree or element structure to sys.stdout. This
  1020. # function should be used for debugging only.
  1021. # <p>
  1022. # The exact output format is implementation dependent. In this
  1023. # version, it's written as an ordinary XML file.
  1024. #
  1025. # @param elem An element tree or an individual element.
  1026. def dump(elem):
  1027. # debugging
  1028. if not isinstance(elem, ElementTree):
  1029. elem = ElementTree(elem)
  1030. elem.write(sys.stdout)
  1031. tail = elem.getroot().tail
  1032. if not tail or tail[-1] != "\n":
  1033. sys.stdout.write("\n")
  1034. # --------------------------------------------------------------------
  1035. # parsing
  1036. ##
  1037. # Parses an XML document into an element tree.
  1038. #
  1039. # @param source A filename or file object containing XML data.
  1040. # @param parser An optional parser instance. If not given, the
  1041. # standard {@link XMLParser} parser is used.
  1042. # @return An ElementTree instance
  1043. def parse(source, parser=None):
  1044. tree = ElementTree()
  1045. tree.parse(source, parser)
  1046. return tree
  1047. ##
  1048. # Parses an XML document into an element tree incrementally, and reports
  1049. # what's going on to the user.
  1050. #
  1051. # @param source A filename or file object containing XML data.
  1052. # @param events A list of events to report back. If omitted, only "end"
  1053. # events are reported.
  1054. # @param parser An optional parser instance. If not given, the
  1055. # standard {@link XMLParser} parser is used.
  1056. # @return A (event, elem) iterator.
  1057. def iterparse(source, events=None, parser=None):
  1058. if sys.platform == 'cli':
  1059. raise NotImplementedError('iterparse is not supported on IronPython. (CP #31923)')
  1060. if not hasattr(source, "read"):
  1061. source = open(source, "rb")
  1062. close_source = True
  1063. try:
  1064. if not parser:
  1065. parser = XMLParser(target=TreeBuilder())
  1066. return _IterParseIterator(source, events, parser, close_source)
  1067. except:
  1068. if close_source:
  1069. source.close()
  1070. raise
  1071. class _IterParseIterator(object):
  1072. def __init__(self, source, events, parser, close_source=False):
  1073. self._file = source
  1074. self._close_file = close_source
  1075. self._events = []
  1076. self._index = 0
  1077. self._error = None
  1078. self.root = self._root = None
  1079. self._parser = parser
  1080. # wire up the parser for event reporting
  1081. parser = self._parser._parser
  1082. append = self._events.append
  1083. if events is None:
  1084. events = ["end"]
  1085. for event in events:
  1086. if event == "start":
  1087. try:
  1088. parser.ordered_attributes = 1
  1089. parser.specified_attributes = 1
  1090. def handler(tag, attrib_in, event=event, append=append,
  1091. start=self._parser._start_list):
  1092. append((event, start(tag, attrib_in)))
  1093. parser.StartElementHandler = handler
  1094. except AttributeError:
  1095. def handler(tag, attrib_in, event=event, append=append,
  1096. start=self._parser._start):
  1097. append((event, start(tag, attrib_in)))
  1098. parser.StartElementHandler = handler
  1099. elif event == "end":
  1100. def handler(tag, event=event, append=append,
  1101. end=self._parser._end):
  1102. append((event, end(tag)))
  1103. parser.EndElementHandler = handler
  1104. elif event == "start-ns":
  1105. def handler(prefix, uri, event=event, append=append):
  1106. try:
  1107. uri = (uri or "").encode("ascii")
  1108. except UnicodeError:
  1109. pass
  1110. append((event, (prefix or "", uri or "")))
  1111. parser.StartNamespaceDeclHandler = handler
  1112. elif event == "end-ns":
  1113. def handler(prefix, event=event, append=append):
  1114. append((event, None))
  1115. parser.EndNamespaceDeclHandler = handler
  1116. else:
  1117. raise ValueError("unknown event %r" % event)
  1118. def next(self):
  1119. try:
  1120. while 1:
  1121. try:
  1122. item = self._events[self._index]
  1123. self._index += 1
  1124. return item
  1125. except IndexError:
  1126. pass
  1127. if self._error:
  1128. e = self._error
  1129. self._error = None
  1130. raise e
  1131. if self._parser is None:
  1132. self.root = self._root
  1133. break
  1134. # load event buffer
  1135. del self._events[:]
  1136. self._index = 0
  1137. data = self._file.read(16384)
  1138. if data:
  1139. try:
  1140. self._parser.feed(data)
  1141. except SyntaxError as exc:
  1142. self._error = exc
  1143. else:
  1144. self._root = self._parser.close()
  1145. self._parser = None
  1146. except:
  1147. if self._close_file:
  1148. self._file.close()
  1149. raise
  1150. if self._close_file:
  1151. self._file.close()
  1152. raise StopIteration
  1153. def __iter__(self):
  1154. return self
  1155. ##
  1156. # Parses an XML document from a string constant. This function can
  1157. # be used to embed "XML literals" in Python code.
  1158. #
  1159. # @param source A string containing XML data.
  1160. # @param parser An optional parser instance. If not given, the
  1161. # standard {@link XMLParser} parser is used.
  1162. # @return An Element instance.
  1163. # @defreturn Element
  1164. def XML(text, parser=None):
  1165. if not parser:
  1166. parser = XMLParser(target=TreeBuilder())
  1167. parser.feed(text)
  1168. return parser.close()
  1169. ##
  1170. # Parses an XML document from a string constant, and also returns
  1171. # a dictionary which maps from element id:s to elements.
  1172. #
  1173. # @param source A string containing XML data.
  1174. # @param parser An optional parser instance. If not given, the
  1175. # standard {@link XMLParser} parser is used.
  1176. # @return A tuple containing an Element instance and a dictionary.
  1177. # @defreturn (Element, dictionary)
  1178. def XMLID(text, parser=None):
  1179. if not parser:
  1180. parser = XMLParser(target=TreeBuilder())
  1181. parser.feed(text)
  1182. tree = parser.close()
  1183. ids = {}
  1184. for elem in tree.iter():
  1185. id = elem.get("id")
  1186. if id:
  1187. ids[id] = elem
  1188. return tree, ids
  1189. ##
  1190. # Parses an XML document from a string constant. Same as {@link #XML}.
  1191. #
  1192. # @def fromstring(text)
  1193. # @param source A string containing XML data.
  1194. # @return An Element instance.
  1195. # @defreturn Element
  1196. fromstring = XML
  1197. ##
  1198. # Parses an XML document from a sequence of string fragments.
  1199. #
  1200. # @param sequence A list or other sequence containing XML data fragments.
  1201. # @param parser An optional parser instance. If not given, the
  1202. # standard {@link XMLParser} parser is used.
  1203. # @return An Element instance.
  1204. # @defreturn Element
  1205. # @since 1.3
  1206. def fromstringlist(sequence, parser=None):
  1207. if not parser:
  1208. parser = XMLParser(target=TreeBuilder())
  1209. for text in sequence:
  1210. parser.feed(text)
  1211. return parser.close()
  1212. # --------------------------------------------------------------------
  1213. ##
  1214. # Generic element structure builder. This builder converts a sequence
  1215. # of {@link #TreeBuilder.start}, {@link #TreeBuilder.data}, and {@link
  1216. # #TreeBuilder.end} method calls to a well-formed element structure.
  1217. # <p>
  1218. # You can use this class to build an element structure using a custom XML
  1219. # parser, or a parser for some other XML-like format.
  1220. #
  1221. # @param element_factory Optional element factory. This factory
  1222. # is called to create new Element instances, as necessary.
  1223. class TreeBuilder(object):
  1224. def __init__(self, element_factory=None):
  1225. self._data = [] # data collector
  1226. self._elem = [] # element stack
  1227. self._last = None # last element
  1228. self._tail = None # true if we're after an end tag
  1229. if element_factory is None:
  1230. element_factory = Element
  1231. self._factory = element_factory
  1232. ##
  1233. # Flushes the builder buffers, and returns the toplevel document
  1234. # element.
  1235. #
  1236. # @return An Element instance.
  1237. # @defreturn Element
  1238. def close(self):
  1239. assert len(self._elem) == 0, "missing end tags"
  1240. assert self._last is not None, "missing toplevel element"
  1241. return self._last
  1242. def _flush(self):
  1243. if self._data:
  1244. if self._last is not None:
  1245. text = "".join(self._data)
  1246. if self._tail:
  1247. assert self._last.tail is None, "internal error (tail)"
  1248. self._last.tail = text
  1249. else:
  1250. assert self._last.text is None, "internal error (text)"
  1251. self._last.text = text
  1252. self._data = []
  1253. ##
  1254. # Adds text to the current element.
  1255. #
  1256. # @param data A string. This should be either an 8-bit string
  1257. # containing ASCII text, or a Unicode string.
  1258. def data(self, data):
  1259. self._data.append(data)
  1260. ##
  1261. # Opens a new element.
  1262. #
  1263. # @param tag The element name.
  1264. # @param attrib A dictionary containing element attributes.
  1265. # @return The opened element.
  1266. # @defreturn Element
  1267. def start(self, tag, attrs):
  1268. self._flush()
  1269. self._last = elem = self._factory(tag, attrs)
  1270. if self._elem:
  1271. self._elem[-1].append(elem)
  1272. self._elem.append(elem)
  1273. self._tail = 0
  1274. return elem
  1275. ##
  1276. # Closes the current element.
  1277. #
  1278. # @param tag The element name.
  1279. # @return The closed element.
  1280. # @defreturn Element
  1281. def end(self, tag):
  1282. self._flush()
  1283. self._last = self._elem.pop()
  1284. assert self._last.tag == tag,\
  1285. "end tag mismatch (expected %s, got %s)" % (
  1286. self._last.tag, tag)
  1287. self._tail = 1
  1288. return self._last
  1289. ##
  1290. # Element structure builder for XML source data, based on the
  1291. # <b>expat</b> parser.
  1292. #
  1293. # @keyparam target Target object. If omitted, the builder uses an
  1294. # instance of the standard {@link #TreeBuilder} class.
  1295. # @keyparam html Predefine HTML entities. This flag is not supported
  1296. # by the current implementation.
  1297. # @keyparam encoding Optional encoding. If given, the value overrides
  1298. # the encoding specified in the XML file.
  1299. # @see #ElementTree
  1300. # @see #TreeBuilder
  1301. class XMLParser(object):
  1302. def __init__(self, html=0, target=None, encoding=None):
  1303. try:
  1304. from xml.parsers import expat
  1305. except ImportError:
  1306. try:
  1307. import pyexpat as expat
  1308. except ImportError:
  1309. raise ImportError(
  1310. "No module named expat; use SimpleXMLTreeBuilder instead"
  1311. )
  1312. parser = expat.ParserCreate(encoding, "}")
  1313. if target is None:
  1314. target = TreeBuilder()
  1315. # underscored names are provided for compatibility only
  1316. self.parser = self._parser = parser
  1317. self.target = self._target = target
  1318. self._error = expat.error
  1319. self._names = {} # name memo cache
  1320. # callbacks
  1321. parser.DefaultHandlerExpand = self._default
  1322. parser.StartElementHandler = self._start
  1323. parser.EndElementHandler = self._end
  1324. parser.CharacterDataHandler = self._data
  1325. # optional callbacks
  1326. parser.CommentHandler = self._comment
  1327. parser.ProcessingInstructionHandler = self._pi
  1328. # let expat do the buffering, if supported
  1329. try:
  1330. self._parser.buffer_text = 1
  1331. except AttributeError:
  1332. pass
  1333. # use new-style attribute handling, if supported
  1334. try:
  1335. self._parser.ordered_attributes = 1
  1336. self._parser.specified_attributes = 1
  1337. parser.StartElementHandler = self._start_list
  1338. except AttributeError:
  1339. pass
  1340. self._doctype = None
  1341. self.entity = {}
  1342. try:
  1343. self.version = "Expat %d.%d.%d" % expat.version_info
  1344. except AttributeError:
  1345. pass # unknown
  1346. def _raiseerror(self, value):
  1347. err = ParseError(value)
  1348. err.code = value.code
  1349. err.position = value.lineno, value.offset
  1350. raise err
  1351. def _fixtext(self, text):
  1352. # convert text string to ascii, if possible
  1353. try:
  1354. return text.encode("ascii")
  1355. except UnicodeError:
  1356. return text
  1357. def _fixname(self, key):
  1358. # expand qname, and convert name string to ascii, if possible
  1359. try:
  1360. name = self._names[key]
  1361. except KeyError:
  1362. name = key
  1363. if "}" in name:
  1364. name = "{" + name
  1365. self._names[key] = name = self._fixtext(name)
  1366. return name
  1367. def _start(self, tag, attrib_in):
  1368. fixname = self._fixname
  1369. fixtext = self._fixtext
  1370. tag = fixname(tag)
  1371. attrib = {}
  1372. for key, value in attrib_in.items():
  1373. attrib[fixname(key)] = fixtext(value)
  1374. return self.target.start(tag, attrib)
  1375. def _start_list(self, tag, attrib_in):
  1376. fixname = self._fixname
  1377. fixtext = self._fixtext
  1378. tag = fixname(tag)
  1379. attrib = {}
  1380. if attrib_in:
  1381. for i in range(0, len(attrib_in), 2):
  1382. attrib[fixname(attrib_in[i])] = fixtext(attrib_in[i+1])
  1383. return self.target.start(tag, attrib)
  1384. def _data(self, text):
  1385. return self.target.data(self._fixtext(text))
  1386. def _end(self, tag):
  1387. return self.target.end(self._fixname(tag))
  1388. def _comment(self, data):
  1389. try:
  1390. comment = self.target.comment
  1391. except AttributeError:
  1392. pass
  1393. else:
  1394. return comment(self._fixtext(data))
  1395. def _pi(self, target, data):
  1396. try:
  1397. pi = self.target.pi
  1398. except AttributeError:
  1399. pass
  1400. else:
  1401. return pi(self._fixtext(target), self._fixtext(data))
  1402. def _default(self, text):
  1403. prefix = text[:1]
  1404. if prefix == "&":
  1405. # deal with undefined entities
  1406. try:
  1407. self.target.data(self.entity[text[1:-1]])
  1408. except KeyError:
  1409. from xml.parsers import expat
  1410. err = expat.error(
  1411. "undefined entity %s: line %d, column %d" %
  1412. (text, self._parser.ErrorLineNumber,
  1413. self._parser.ErrorColumnNumber)
  1414. )
  1415. err.code = 11 # XML_ERROR_UNDEFINED_ENTITY
  1416. err.lineno = self._parser.ErrorLineNumber
  1417. err.offset = self._parser.ErrorColumnNumber
  1418. raise err
  1419. elif prefix == "<" and text[:9] == "<!DOCTYPE":
  1420. self._doctype = [] # inside a doctype declaration
  1421. elif self._doctype is not None:
  1422. # parse doctype contents
  1423. if prefix == ">":
  1424. self._doctype = None
  1425. return
  1426. text = text.strip()
  1427. if not text:
  1428. return
  1429. self._doctype.append(text)
  1430. n = len(self._doctype)
  1431. if n > 2:
  1432. type = self._doctype[1]
  1433. if type == "PUBLIC" and n == 4:
  1434. name, type, pubid, system = self._doctype
  1435. elif type == "SYSTEM" and n == 3:
  1436. name, type, system = self._doctype
  1437. pubid = None
  1438. else:
  1439. return
  1440. if pubid:
  1441. pubid = pubid[1:-1]
  1442. if hasattr(self.target, "doctype"):
  1443. self.target.doctype(name, pubid, system[1:-1])
  1444. elif self.doctype is not self._XMLParser__doctype:
  1445. # warn about deprecated call
  1446. self._XMLParser__doctype(name, pubid, system[1:-1])
  1447. self.doctype(name, pubid, system[1:-1])
  1448. self._doctype = None
  1449. ##
  1450. # (Deprecated) Handles a doctype declaration.
  1451. #
  1452. # @param name Doctype name.
  1453. # @param pubid Public identifier.
  1454. # @param system System identifier.
  1455. def doctype(self, name, pubid, system):
  1456. """This method of XMLParser is deprecated."""
  1457. warnings.warn(
  1458. "This method of XMLParser is deprecated. Define doctype() "
  1459. "method on the TreeBuilder target.",
  1460. DeprecationWarning,
  1461. )
  1462. # sentinel, if doctype is redefined in a subclass
  1463. __doctype = doctype
  1464. ##
  1465. # Feeds data to the parser.
  1466. #
  1467. # @param data Encoded data.
  1468. def feed(self, data):
  1469. try:
  1470. self._parser.Parse(data, 0)
  1471. except self._error, v:
  1472. self._raiseerror(v)
  1473. ##
  1474. # Finishes feeding data to the parser.
  1475. #
  1476. # @return An element structure.
  1477. # @defreturn Element
  1478. def close(self):
  1479. try:
  1480. self._parser.Parse("", 1) # end of data
  1481. except self._error, v:
  1482. self._raiseerror(v)
  1483. tree = self.target.close()
  1484. del self.target, self._parser # get rid of circular references
  1485. return tree
  1486. if sys.platform == 'cli':
  1487. from . import SimpleXMLTreeBuilder
  1488. XMLParser = SimpleXMLTreeBuilder.TreeBuilder
  1489. # compatibility
  1490. XMLTreeBuilder = XMLParser
  1491. # workaround circular import.
  1492. try:
  1493. from ElementC14N import _serialize_c14n
  1494. _serialize["c14n"] = _serialize_c14n
  1495. except ImportError:
  1496. pass