/Lib/xml/etree/ElementTree.py

http://unladen-swallow.googlecode.com/ · Python · 1260 lines · 588 code · 153 blank · 519 comment · 149 complexity · 6556d86428b61f94ae07fd61c75146f6 MD5 · raw file

  1. #
  2. # ElementTree
  3. # $Id: ElementTree.py 2326 2005-03-17 07:45:21Z fredrik $
  4. #
  5. # light-weight XML support for Python 1.5.2 and later.
  6. #
  7. # history:
  8. # 2001-10-20 fl created (from various sources)
  9. # 2001-11-01 fl return root from parse method
  10. # 2002-02-16 fl sort attributes in lexical order
  11. # 2002-04-06 fl TreeBuilder refactoring, added PythonDoc markup
  12. # 2002-05-01 fl finished TreeBuilder refactoring
  13. # 2002-07-14 fl added basic namespace support to ElementTree.write
  14. # 2002-07-25 fl added QName attribute support
  15. # 2002-10-20 fl fixed encoding in write
  16. # 2002-11-24 fl changed default encoding to ascii; fixed attribute encoding
  17. # 2002-11-27 fl accept file objects or file names for parse/write
  18. # 2002-12-04 fl moved XMLTreeBuilder back to this module
  19. # 2003-01-11 fl fixed entity encoding glitch for us-ascii
  20. # 2003-02-13 fl added XML literal factory
  21. # 2003-02-21 fl added ProcessingInstruction/PI factory
  22. # 2003-05-11 fl added tostring/fromstring helpers
  23. # 2003-05-26 fl added ElementPath support
  24. # 2003-07-05 fl added makeelement factory method
  25. # 2003-07-28 fl added more well-known namespace prefixes
  26. # 2003-08-15 fl fixed typo in ElementTree.findtext (Thomas Dartsch)
  27. # 2003-09-04 fl fall back on emulator if ElementPath is not installed
  28. # 2003-10-31 fl markup updates
  29. # 2003-11-15 fl fixed nested namespace bug
  30. # 2004-03-28 fl added XMLID helper
  31. # 2004-06-02 fl added default support to findtext
  32. # 2004-06-08 fl fixed encoding of non-ascii element/attribute names
  33. # 2004-08-23 fl take advantage of post-2.1 expat features
  34. # 2005-02-01 fl added iterparse implementation
  35. # 2005-03-02 fl fixed iterparse support for pre-2.2 versions
  36. #
  37. # Copyright (c) 1999-2005 by Fredrik Lundh. All rights reserved.
  38. #
  39. # fredrik@pythonware.com
  40. # http://www.pythonware.com
  41. #
  42. # --------------------------------------------------------------------
  43. # The ElementTree toolkit is
  44. #
  45. # Copyright (c) 1999-2005 by Fredrik Lundh
  46. #
  47. # By obtaining, using, and/or copying this software and/or its
  48. # associated documentation, you agree that you have read, understood,
  49. # and will comply with the following terms and conditions:
  50. #
  51. # Permission to use, copy, modify, and distribute this software and
  52. # its associated documentation for any purpose and without fee is
  53. # hereby granted, provided that the above copyright notice appears in
  54. # all copies, and that both that copyright notice and this permission
  55. # notice appear in supporting documentation, and that the name of
  56. # Secret Labs AB or the author not be used in advertising or publicity
  57. # pertaining to distribution of the software without specific, written
  58. # prior permission.
  59. #
  60. # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  61. # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
  62. # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
  63. # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
  64. # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  65. # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
  66. # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  67. # OF THIS SOFTWARE.
  68. # --------------------------------------------------------------------
  69. # Licensed to PSF under a Contributor Agreement.
  70. # See http://www.python.org/2.4/license for licensing details.
  71. __all__ = [
  72. # public symbols
  73. "Comment",
  74. "dump",
  75. "Element", "ElementTree",
  76. "fromstring",
  77. "iselement", "iterparse",
  78. "parse",
  79. "PI", "ProcessingInstruction",
  80. "QName",
  81. "SubElement",
  82. "tostring",
  83. "TreeBuilder",
  84. "VERSION", "XML",
  85. "XMLParser", "XMLTreeBuilder",
  86. ]
  87. ##
  88. # The <b>Element</b> type is a flexible container object, designed to
  89. # store hierarchical data structures in memory. The type can be
  90. # described as a cross between a list and a dictionary.
  91. # <p>
  92. # Each element has a number of properties associated with it:
  93. # <ul>
  94. # <li>a <i>tag</i>. This is a string identifying what kind of data
  95. # this element represents (the element type, in other words).</li>
  96. # <li>a number of <i>attributes</i>, stored in a Python dictionary.</li>
  97. # <li>a <i>text</i> string.</li>
  98. # <li>an optional <i>tail</i> string.</li>
  99. # <li>a number of <i>child elements</i>, stored in a Python sequence</li>
  100. # </ul>
  101. #
  102. # To create an element instance, use the {@link #Element} or {@link
  103. # #SubElement} factory functions.
  104. # <p>
  105. # The {@link #ElementTree} class can be used to wrap an element
  106. # structure, and convert it from and to XML.
  107. ##
  108. import string, sys, re
  109. class _SimpleElementPath:
  110. # emulate pre-1.2 find/findtext/findall behaviour
  111. def find(self, element, tag):
  112. for elem in element:
  113. if elem.tag == tag:
  114. return elem
  115. return None
  116. def findtext(self, element, tag, default=None):
  117. for elem in element:
  118. if elem.tag == tag:
  119. return elem.text or ""
  120. return default
  121. def findall(self, element, tag):
  122. if tag[:3] == ".//":
  123. return element.getiterator(tag[3:])
  124. result = []
  125. for elem in element:
  126. if elem.tag == tag:
  127. result.append(elem)
  128. return result
  129. try:
  130. import ElementPath
  131. except ImportError:
  132. # FIXME: issue warning in this case?
  133. ElementPath = _SimpleElementPath()
  134. # TODO: add support for custom namespace resolvers/default namespaces
  135. # TODO: add improved support for incremental parsing
  136. VERSION = "1.2.6"
  137. ##
  138. # Internal element class. This class defines the Element interface,
  139. # and provides a reference implementation of this interface.
  140. # <p>
  141. # You should not create instances of this class directly. Use the
  142. # appropriate factory functions instead, such as {@link #Element}
  143. # and {@link #SubElement}.
  144. #
  145. # @see Element
  146. # @see SubElement
  147. # @see Comment
  148. # @see ProcessingInstruction
  149. class _ElementInterface:
  150. # <tag attrib>text<child/>...</tag>tail
  151. ##
  152. # (Attribute) Element tag.
  153. tag = None
  154. ##
  155. # (Attribute) Element attribute dictionary. Where possible, use
  156. # {@link #_ElementInterface.get},
  157. # {@link #_ElementInterface.set},
  158. # {@link #_ElementInterface.keys}, and
  159. # {@link #_ElementInterface.items} to access
  160. # element attributes.
  161. attrib = None
  162. ##
  163. # (Attribute) Text before first subelement. This is either a
  164. # string or the value None, if there was no text.
  165. text = None
  166. ##
  167. # (Attribute) Text after this element's end tag, but before the
  168. # next sibling element's start tag. This is either a string or
  169. # the value None, if there was no text.
  170. tail = None # text after end tag, if any
  171. def __init__(self, tag, attrib):
  172. self.tag = tag
  173. self.attrib = attrib
  174. self._children = []
  175. def __repr__(self):
  176. return "<Element %s at %x>" % (self.tag, id(self))
  177. ##
  178. # Creates a new element object of the same type as this element.
  179. #
  180. # @param tag Element tag.
  181. # @param attrib Element attributes, given as a dictionary.
  182. # @return A new element instance.
  183. def makeelement(self, tag, attrib):
  184. return Element(tag, attrib)
  185. ##
  186. # Returns the number of subelements.
  187. #
  188. # @return The number of subelements.
  189. def __len__(self):
  190. return len(self._children)
  191. ##
  192. # Returns the given subelement.
  193. #
  194. # @param index What subelement to return.
  195. # @return The given subelement.
  196. # @exception IndexError If the given element does not exist.
  197. def __getitem__(self, index):
  198. return self._children[index]
  199. ##
  200. # Replaces the given subelement.
  201. #
  202. # @param index What subelement to replace.
  203. # @param element The new element value.
  204. # @exception IndexError If the given element does not exist.
  205. # @exception AssertionError If element is not a valid object.
  206. def __setitem__(self, index, element):
  207. assert iselement(element)
  208. self._children[index] = element
  209. ##
  210. # Deletes the given subelement.
  211. #
  212. # @param index What subelement to delete.
  213. # @exception IndexError If the given element does not exist.
  214. def __delitem__(self, index):
  215. del self._children[index]
  216. ##
  217. # Returns a list containing subelements in the given range.
  218. #
  219. # @param start The first subelement to return.
  220. # @param stop The first subelement that shouldn't be returned.
  221. # @return A sequence object containing subelements.
  222. def __getslice__(self, start, stop):
  223. return self._children[start:stop]
  224. ##
  225. # Replaces a number of subelements with elements from a sequence.
  226. #
  227. # @param start The first subelement to replace.
  228. # @param stop The first subelement that shouldn't be replaced.
  229. # @param elements A sequence object with zero or more elements.
  230. # @exception AssertionError If a sequence member is not a valid object.
  231. def __setslice__(self, start, stop, elements):
  232. for element in elements:
  233. assert iselement(element)
  234. self._children[start:stop] = list(elements)
  235. ##
  236. # Deletes a number of subelements.
  237. #
  238. # @param start The first subelement to delete.
  239. # @param stop The first subelement to leave in there.
  240. def __delslice__(self, start, stop):
  241. del self._children[start:stop]
  242. ##
  243. # Adds a subelement to the end of this element.
  244. #
  245. # @param element The element to add.
  246. # @exception AssertionError If a sequence member is not a valid object.
  247. def append(self, element):
  248. assert iselement(element)
  249. self._children.append(element)
  250. ##
  251. # Inserts a subelement at the given position in this element.
  252. #
  253. # @param index Where to insert the new subelement.
  254. # @exception AssertionError If the element is not a valid object.
  255. def insert(self, index, element):
  256. assert iselement(element)
  257. self._children.insert(index, element)
  258. ##
  259. # Removes a matching subelement. Unlike the <b>find</b> methods,
  260. # this method compares elements based on identity, not on tag
  261. # value or contents.
  262. #
  263. # @param element What element to remove.
  264. # @exception ValueError If a matching element could not be found.
  265. # @exception AssertionError If the element is not a valid object.
  266. def remove(self, element):
  267. assert iselement(element)
  268. self._children.remove(element)
  269. ##
  270. # Returns all subelements. The elements are returned in document
  271. # order.
  272. #
  273. # @return A list of subelements.
  274. # @defreturn list of Element instances
  275. def getchildren(self):
  276. return self._children
  277. ##
  278. # Finds the first matching subelement, by tag name or path.
  279. #
  280. # @param path What element to look for.
  281. # @return The first matching element, or None if no element was found.
  282. # @defreturn Element or None
  283. def find(self, path):
  284. return ElementPath.find(self, path)
  285. ##
  286. # Finds text for the first matching subelement, by tag name or path.
  287. #
  288. # @param path What element to look for.
  289. # @param default What to return if the element was not found.
  290. # @return The text content of the first matching element, or the
  291. # default value no element was found. Note that if the element
  292. # has is found, but has no text content, this method returns an
  293. # empty string.
  294. # @defreturn string
  295. def findtext(self, path, default=None):
  296. return ElementPath.findtext(self, path, default)
  297. ##
  298. # Finds all matching subelements, by tag name or path.
  299. #
  300. # @param path What element to look for.
  301. # @return A list or iterator containing all matching elements,
  302. # in document order.
  303. # @defreturn list of Element instances
  304. def findall(self, path):
  305. return ElementPath.findall(self, path)
  306. ##
  307. # Resets an element. This function removes all subelements, clears
  308. # all attributes, and sets the text and tail attributes to None.
  309. def clear(self):
  310. self.attrib.clear()
  311. self._children = []
  312. self.text = self.tail = None
  313. ##
  314. # Gets an element attribute.
  315. #
  316. # @param key What attribute to look for.
  317. # @param default What to return if the attribute was not found.
  318. # @return The attribute value, or the default value, if the
  319. # attribute was not found.
  320. # @defreturn string or None
  321. def get(self, key, default=None):
  322. return self.attrib.get(key, default)
  323. ##
  324. # Sets an element attribute.
  325. #
  326. # @param key What attribute to set.
  327. # @param value The attribute value.
  328. def set(self, key, value):
  329. self.attrib[key] = value
  330. ##
  331. # Gets a list of attribute names. The names are returned in an
  332. # arbitrary order (just like for an ordinary Python dictionary).
  333. #
  334. # @return A list of element attribute names.
  335. # @defreturn list of strings
  336. def keys(self):
  337. return self.attrib.keys()
  338. ##
  339. # Gets element attributes, as a sequence. The attributes are
  340. # returned in an arbitrary order.
  341. #
  342. # @return A list of (name, value) tuples for all attributes.
  343. # @defreturn list of (string, string) tuples
  344. def items(self):
  345. return self.attrib.items()
  346. ##
  347. # Creates a tree iterator. The iterator loops over this element
  348. # and all subelements, in document order, and returns all elements
  349. # with a matching tag.
  350. # <p>
  351. # If the tree structure is modified during iteration, the result
  352. # is undefined.
  353. #
  354. # @param tag What tags to look for (default is to return all elements).
  355. # @return A list or iterator containing all the matching elements.
  356. # @defreturn list or iterator
  357. def getiterator(self, tag=None):
  358. nodes = []
  359. if tag == "*":
  360. tag = None
  361. if tag is None or self.tag == tag:
  362. nodes.append(self)
  363. for node in self._children:
  364. nodes.extend(node.getiterator(tag))
  365. return nodes
  366. # compatibility
  367. _Element = _ElementInterface
  368. ##
  369. # Element factory. This function returns an object implementing the
  370. # standard Element interface. The exact class or type of that object
  371. # is implementation dependent, but it will always be compatible with
  372. # the {@link #_ElementInterface} class in this module.
  373. # <p>
  374. # The element name, attribute names, and attribute values can be
  375. # either 8-bit ASCII strings or Unicode strings.
  376. #
  377. # @param tag The element name.
  378. # @param attrib An optional dictionary, containing element attributes.
  379. # @param **extra Additional attributes, given as keyword arguments.
  380. # @return An element instance.
  381. # @defreturn Element
  382. def Element(tag, attrib={}, **extra):
  383. attrib = attrib.copy()
  384. attrib.update(extra)
  385. return _ElementInterface(tag, attrib)
  386. ##
  387. # Subelement factory. This function creates an element instance, and
  388. # appends it to an existing element.
  389. # <p>
  390. # The element name, attribute names, and attribute values can be
  391. # either 8-bit ASCII strings or Unicode strings.
  392. #
  393. # @param parent The parent element.
  394. # @param tag The subelement name.
  395. # @param attrib An optional dictionary, containing element attributes.
  396. # @param **extra Additional attributes, given as keyword arguments.
  397. # @return An element instance.
  398. # @defreturn Element
  399. def SubElement(parent, tag, attrib={}, **extra):
  400. attrib = attrib.copy()
  401. attrib.update(extra)
  402. element = parent.makeelement(tag, attrib)
  403. parent.append(element)
  404. return element
  405. ##
  406. # Comment element factory. This factory function creates a special
  407. # element that will be serialized as an XML comment.
  408. # <p>
  409. # The comment string can be either an 8-bit ASCII string or a Unicode
  410. # string.
  411. #
  412. # @param text A string containing the comment string.
  413. # @return An element instance, representing a comment.
  414. # @defreturn Element
  415. def Comment(text=None):
  416. element = Element(Comment)
  417. element.text = text
  418. return element
  419. ##
  420. # PI element factory. This factory function creates a special element
  421. # that will be serialized as an XML processing instruction.
  422. #
  423. # @param target A string containing the PI target.
  424. # @param text A string containing the PI contents, if any.
  425. # @return An element instance, representing a PI.
  426. # @defreturn Element
  427. def ProcessingInstruction(target, text=None):
  428. element = Element(ProcessingInstruction)
  429. element.text = target
  430. if text:
  431. element.text = element.text + " " + text
  432. return element
  433. PI = ProcessingInstruction
  434. ##
  435. # QName wrapper. This can be used to wrap a QName attribute value, in
  436. # order to get proper namespace handling on output.
  437. #
  438. # @param text A string containing the QName value, in the form {uri}local,
  439. # or, if the tag argument is given, the URI part of a QName.
  440. # @param tag Optional tag. If given, the first argument is interpreted as
  441. # an URI, and this argument is interpreted as a local name.
  442. # @return An opaque object, representing the QName.
  443. class QName:
  444. def __init__(self, text_or_uri, tag=None):
  445. if tag:
  446. text_or_uri = "{%s}%s" % (text_or_uri, tag)
  447. self.text = text_or_uri
  448. def __str__(self):
  449. return self.text
  450. def __hash__(self):
  451. return hash(self.text)
  452. def __cmp__(self, other):
  453. if isinstance(other, QName):
  454. return cmp(self.text, other.text)
  455. return cmp(self.text, other)
  456. ##
  457. # ElementTree wrapper class. This class represents an entire element
  458. # hierarchy, and adds some extra support for serialization to and from
  459. # standard XML.
  460. #
  461. # @param element Optional root element.
  462. # @keyparam file Optional file handle or name. If given, the
  463. # tree is initialized with the contents of this XML file.
  464. class ElementTree:
  465. def __init__(self, element=None, file=None):
  466. assert element is None or iselement(element)
  467. self._root = element # first node
  468. if file:
  469. self.parse(file)
  470. ##
  471. # Gets the root element for this tree.
  472. #
  473. # @return An element instance.
  474. # @defreturn Element
  475. def getroot(self):
  476. return self._root
  477. ##
  478. # Replaces the root element for this tree. This discards the
  479. # current contents of the tree, and replaces it with the given
  480. # element. Use with care.
  481. #
  482. # @param element An element instance.
  483. def _setroot(self, element):
  484. assert iselement(element)
  485. self._root = element
  486. ##
  487. # Loads an external XML document into this element tree.
  488. #
  489. # @param source A file name or file object.
  490. # @param parser An optional parser instance. If not given, the
  491. # standard {@link XMLTreeBuilder} parser is used.
  492. # @return The document root element.
  493. # @defreturn Element
  494. def parse(self, source, parser=None):
  495. if not hasattr(source, "read"):
  496. source = open(source, "rb")
  497. if not parser:
  498. parser = XMLTreeBuilder()
  499. while 1:
  500. data = source.read(32768)
  501. if not data:
  502. break
  503. parser.feed(data)
  504. self._root = parser.close()
  505. return self._root
  506. ##
  507. # Creates a tree iterator for the root element. The iterator loops
  508. # over all elements in this tree, in document order.
  509. #
  510. # @param tag What tags to look for (default is to return all elements)
  511. # @return An iterator.
  512. # @defreturn iterator
  513. def getiterator(self, tag=None):
  514. assert self._root is not None
  515. return self._root.getiterator(tag)
  516. ##
  517. # Finds the first toplevel element with given tag.
  518. # Same as getroot().find(path).
  519. #
  520. # @param path What element to look for.
  521. # @return The first matching element, or None if no element was found.
  522. # @defreturn Element or None
  523. def find(self, path):
  524. assert self._root is not None
  525. if path[:1] == "/":
  526. path = "." + path
  527. return self._root.find(path)
  528. ##
  529. # Finds the element text for the first toplevel element with given
  530. # tag. Same as getroot().findtext(path).
  531. #
  532. # @param path What toplevel element to look for.
  533. # @param default What to return if the element was not found.
  534. # @return The text content of the first matching element, or the
  535. # default value no element was found. Note that if the element
  536. # has is found, but has no text content, this method returns an
  537. # empty string.
  538. # @defreturn string
  539. def findtext(self, path, default=None):
  540. assert self._root is not None
  541. if path[:1] == "/":
  542. path = "." + path
  543. return self._root.findtext(path, default)
  544. ##
  545. # Finds all toplevel elements with the given tag.
  546. # Same as getroot().findall(path).
  547. #
  548. # @param path What element to look for.
  549. # @return A list or iterator containing all matching elements,
  550. # in document order.
  551. # @defreturn list of Element instances
  552. def findall(self, path):
  553. assert self._root is not None
  554. if path[:1] == "/":
  555. path = "." + path
  556. return self._root.findall(path)
  557. ##
  558. # Writes the element tree to a file, as XML.
  559. #
  560. # @param file A file name, or a file object opened for writing.
  561. # @param encoding Optional output encoding (default is US-ASCII).
  562. def write(self, file, encoding="us-ascii"):
  563. assert self._root is not None
  564. if not hasattr(file, "write"):
  565. file = open(file, "wb")
  566. if not encoding:
  567. encoding = "us-ascii"
  568. elif encoding != "utf-8" and encoding != "us-ascii":
  569. file.write("<?xml version='1.0' encoding='%s'?>\n" % encoding)
  570. self._write(file, self._root, encoding, {})
  571. def _write(self, file, node, encoding, namespaces):
  572. # write XML to file
  573. tag = node.tag
  574. if tag is Comment:
  575. file.write("<!-- %s -->" % _escape_cdata(node.text, encoding))
  576. elif tag is ProcessingInstruction:
  577. file.write("<?%s?>" % _escape_cdata(node.text, encoding))
  578. else:
  579. items = node.items()
  580. xmlns_items = [] # new namespaces in this scope
  581. try:
  582. if isinstance(tag, QName) or tag[:1] == "{":
  583. tag, xmlns = fixtag(tag, namespaces)
  584. if xmlns: xmlns_items.append(xmlns)
  585. except TypeError:
  586. _raise_serialization_error(tag)
  587. file.write("<" + _encode(tag, encoding))
  588. if items or xmlns_items:
  589. items.sort() # lexical order
  590. for k, v in items:
  591. try:
  592. if isinstance(k, QName) or k[:1] == "{":
  593. k, xmlns = fixtag(k, namespaces)
  594. if xmlns: xmlns_items.append(xmlns)
  595. except TypeError:
  596. _raise_serialization_error(k)
  597. try:
  598. if isinstance(v, QName):
  599. v, xmlns = fixtag(v, namespaces)
  600. if xmlns: xmlns_items.append(xmlns)
  601. except TypeError:
  602. _raise_serialization_error(v)
  603. file.write(" %s=\"%s\"" % (_encode(k, encoding),
  604. _escape_attrib(v, encoding)))
  605. for k, v in xmlns_items:
  606. file.write(" %s=\"%s\"" % (_encode(k, encoding),
  607. _escape_attrib(v, encoding)))
  608. if node.text or len(node):
  609. file.write(">")
  610. if node.text:
  611. file.write(_escape_cdata(node.text, encoding))
  612. for n in node:
  613. self._write(file, n, encoding, namespaces)
  614. file.write("</" + _encode(tag, encoding) + ">")
  615. else:
  616. file.write(" />")
  617. for k, v in xmlns_items:
  618. del namespaces[v]
  619. if node.tail:
  620. file.write(_escape_cdata(node.tail, encoding))
  621. # --------------------------------------------------------------------
  622. # helpers
  623. ##
  624. # Checks if an object appears to be a valid element object.
  625. #
  626. # @param An element instance.
  627. # @return A true value if this is an element object.
  628. # @defreturn flag
  629. def iselement(element):
  630. # FIXME: not sure about this; might be a better idea to look
  631. # for tag/attrib/text attributes
  632. return isinstance(element, _ElementInterface) or hasattr(element, "tag")
  633. ##
  634. # Writes an element tree or element structure to sys.stdout. This
  635. # function should be used for debugging only.
  636. # <p>
  637. # The exact output format is implementation dependent. In this
  638. # version, it's written as an ordinary XML file.
  639. #
  640. # @param elem An element tree or an individual element.
  641. def dump(elem):
  642. # debugging
  643. if not isinstance(elem, ElementTree):
  644. elem = ElementTree(elem)
  645. elem.write(sys.stdout)
  646. tail = elem.getroot().tail
  647. if not tail or tail[-1] != "\n":
  648. sys.stdout.write("\n")
  649. def _encode(s, encoding):
  650. try:
  651. return s.encode(encoding)
  652. except AttributeError:
  653. return s # 1.5.2: assume the string uses the right encoding
  654. if sys.version[:3] == "1.5":
  655. _escape = re.compile(r"[&<>\"\x80-\xff]+") # 1.5.2
  656. else:
  657. _escape = re.compile(eval(r'u"[&<>\"\u0080-\uffff]+"'))
  658. _escape_map = {
  659. "&": "&amp;",
  660. "<": "&lt;",
  661. ">": "&gt;",
  662. '"': "&quot;",
  663. }
  664. _namespace_map = {
  665. # "well-known" namespace prefixes
  666. "http://www.w3.org/XML/1998/namespace": "xml",
  667. "http://www.w3.org/1999/xhtml": "html",
  668. "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
  669. "http://schemas.xmlsoap.org/wsdl/": "wsdl",
  670. }
  671. def _raise_serialization_error(text):
  672. raise TypeError(
  673. "cannot serialize %r (type %s)" % (text, type(text).__name__)
  674. )
  675. def _encode_entity(text, pattern=_escape):
  676. # map reserved and non-ascii characters to numerical entities
  677. def escape_entities(m, map=_escape_map):
  678. out = []
  679. append = out.append
  680. for char in m.group():
  681. text = map.get(char)
  682. if text is None:
  683. text = "&#%d;" % ord(char)
  684. append(text)
  685. return string.join(out, "")
  686. try:
  687. return _encode(pattern.sub(escape_entities, text), "ascii")
  688. except TypeError:
  689. _raise_serialization_error(text)
  690. #
  691. # the following functions assume an ascii-compatible encoding
  692. # (or "utf-16")
  693. def _escape_cdata(text, encoding=None, replace=string.replace):
  694. # escape character data
  695. try:
  696. if encoding:
  697. try:
  698. text = _encode(text, encoding)
  699. except UnicodeError:
  700. return _encode_entity(text)
  701. text = replace(text, "&", "&amp;")
  702. text = replace(text, "<", "&lt;")
  703. text = replace(text, ">", "&gt;")
  704. return text
  705. except (TypeError, AttributeError):
  706. _raise_serialization_error(text)
  707. def _escape_attrib(text, encoding=None, replace=string.replace):
  708. # escape attribute value
  709. try:
  710. if encoding:
  711. try:
  712. text = _encode(text, encoding)
  713. except UnicodeError:
  714. return _encode_entity(text)
  715. text = replace(text, "&", "&amp;")
  716. text = replace(text, "'", "&apos;") # FIXME: overkill
  717. text = replace(text, "\"", "&quot;")
  718. text = replace(text, "<", "&lt;")
  719. text = replace(text, ">", "&gt;")
  720. return text
  721. except (TypeError, AttributeError):
  722. _raise_serialization_error(text)
  723. def fixtag(tag, namespaces):
  724. # given a decorated tag (of the form {uri}tag), return prefixed
  725. # tag and namespace declaration, if any
  726. if isinstance(tag, QName):
  727. tag = tag.text
  728. namespace_uri, tag = string.split(tag[1:], "}", 1)
  729. prefix = namespaces.get(namespace_uri)
  730. if prefix is None:
  731. prefix = _namespace_map.get(namespace_uri)
  732. if prefix is None:
  733. prefix = "ns%d" % len(namespaces)
  734. namespaces[namespace_uri] = prefix
  735. if prefix == "xml":
  736. xmlns = None
  737. else:
  738. xmlns = ("xmlns:%s" % prefix, namespace_uri)
  739. else:
  740. xmlns = None
  741. return "%s:%s" % (prefix, tag), xmlns
  742. ##
  743. # Parses an XML document into an element tree.
  744. #
  745. # @param source A filename or file object containing XML data.
  746. # @param parser An optional parser instance. If not given, the
  747. # standard {@link XMLTreeBuilder} parser is used.
  748. # @return An ElementTree instance
  749. def parse(source, parser=None):
  750. tree = ElementTree()
  751. tree.parse(source, parser)
  752. return tree
  753. ##
  754. # Parses an XML document into an element tree incrementally, and reports
  755. # what's going on to the user.
  756. #
  757. # @param source A filename or file object containing XML data.
  758. # @param events A list of events to report back. If omitted, only "end"
  759. # events are reported.
  760. # @return A (event, elem) iterator.
  761. class iterparse:
  762. def __init__(self, source, events=None):
  763. if not hasattr(source, "read"):
  764. source = open(source, "rb")
  765. self._file = source
  766. self._events = []
  767. self._index = 0
  768. self.root = self._root = None
  769. self._parser = XMLTreeBuilder()
  770. # wire up the parser for event reporting
  771. parser = self._parser._parser
  772. append = self._events.append
  773. if events is None:
  774. events = ["end"]
  775. for event in events:
  776. if event == "start":
  777. try:
  778. parser.ordered_attributes = 1
  779. parser.specified_attributes = 1
  780. def handler(tag, attrib_in, event=event, append=append,
  781. start=self._parser._start_list):
  782. append((event, start(tag, attrib_in)))
  783. parser.StartElementHandler = handler
  784. except AttributeError:
  785. def handler(tag, attrib_in, event=event, append=append,
  786. start=self._parser._start):
  787. append((event, start(tag, attrib_in)))
  788. parser.StartElementHandler = handler
  789. elif event == "end":
  790. def handler(tag, event=event, append=append,
  791. end=self._parser._end):
  792. append((event, end(tag)))
  793. parser.EndElementHandler = handler
  794. elif event == "start-ns":
  795. def handler(prefix, uri, event=event, append=append):
  796. try:
  797. uri = _encode(uri, "ascii")
  798. except UnicodeError:
  799. pass
  800. append((event, (prefix or "", uri)))
  801. parser.StartNamespaceDeclHandler = handler
  802. elif event == "end-ns":
  803. def handler(prefix, event=event, append=append):
  804. append((event, None))
  805. parser.EndNamespaceDeclHandler = handler
  806. def next(self):
  807. while 1:
  808. try:
  809. item = self._events[self._index]
  810. except IndexError:
  811. if self._parser is None:
  812. self.root = self._root
  813. try:
  814. raise StopIteration
  815. except NameError:
  816. raise IndexError
  817. # load event buffer
  818. del self._events[:]
  819. self._index = 0
  820. data = self._file.read(16384)
  821. if data:
  822. self._parser.feed(data)
  823. else:
  824. self._root = self._parser.close()
  825. self._parser = None
  826. else:
  827. self._index = self._index + 1
  828. return item
  829. try:
  830. iter
  831. def __iter__(self):
  832. return self
  833. except NameError:
  834. def __getitem__(self, index):
  835. return self.next()
  836. ##
  837. # Parses an XML document from a string constant. This function can
  838. # be used to embed "XML literals" in Python code.
  839. #
  840. # @param source A string containing XML data.
  841. # @return An Element instance.
  842. # @defreturn Element
  843. def XML(text):
  844. parser = XMLTreeBuilder()
  845. parser.feed(text)
  846. return parser.close()
  847. ##
  848. # Parses an XML document from a string constant, and also returns
  849. # a dictionary which maps from element id:s to elements.
  850. #
  851. # @param source A string containing XML data.
  852. # @return A tuple containing an Element instance and a dictionary.
  853. # @defreturn (Element, dictionary)
  854. def XMLID(text):
  855. parser = XMLTreeBuilder()
  856. parser.feed(text)
  857. tree = parser.close()
  858. ids = {}
  859. for elem in tree.getiterator():
  860. id = elem.get("id")
  861. if id:
  862. ids[id] = elem
  863. return tree, ids
  864. ##
  865. # Parses an XML document from a string constant. Same as {@link #XML}.
  866. #
  867. # @def fromstring(text)
  868. # @param source A string containing XML data.
  869. # @return An Element instance.
  870. # @defreturn Element
  871. fromstring = XML
  872. ##
  873. # Generates a string representation of an XML element, including all
  874. # subelements.
  875. #
  876. # @param element An Element instance.
  877. # @return An encoded string containing the XML data.
  878. # @defreturn string
  879. def tostring(element, encoding=None):
  880. class dummy:
  881. pass
  882. data = []
  883. file = dummy()
  884. file.write = data.append
  885. ElementTree(element).write(file, encoding)
  886. return string.join(data, "")
  887. ##
  888. # Generic element structure builder. This builder converts a sequence
  889. # of {@link #TreeBuilder.start}, {@link #TreeBuilder.data}, and {@link
  890. # #TreeBuilder.end} method calls to a well-formed element structure.
  891. # <p>
  892. # You can use this class to build an element structure using a custom XML
  893. # parser, or a parser for some other XML-like format.
  894. #
  895. # @param element_factory Optional element factory. This factory
  896. # is called to create new Element instances, as necessary.
  897. class TreeBuilder:
  898. def __init__(self, element_factory=None):
  899. self._data = [] # data collector
  900. self._elem = [] # element stack
  901. self._last = None # last element
  902. self._tail = None # true if we're after an end tag
  903. if element_factory is None:
  904. element_factory = _ElementInterface
  905. self._factory = element_factory
  906. ##
  907. # Flushes the parser buffers, and returns the toplevel documen
  908. # element.
  909. #
  910. # @return An Element instance.
  911. # @defreturn Element
  912. def close(self):
  913. assert len(self._elem) == 0, "missing end tags"
  914. assert self._last != None, "missing toplevel element"
  915. return self._last
  916. def _flush(self):
  917. if self._data:
  918. if self._last is not None:
  919. text = string.join(self._data, "")
  920. if self._tail:
  921. assert self._last.tail is None, "internal error (tail)"
  922. self._last.tail = text
  923. else:
  924. assert self._last.text is None, "internal error (text)"
  925. self._last.text = text
  926. self._data = []
  927. ##
  928. # Adds text to the current element.
  929. #
  930. # @param data A string. This should be either an 8-bit string
  931. # containing ASCII text, or a Unicode string.
  932. def data(self, data):
  933. self._data.append(data)
  934. ##
  935. # Opens a new element.
  936. #
  937. # @param tag The element name.
  938. # @param attrib A dictionary containing element attributes.
  939. # @return The opened element.
  940. # @defreturn Element
  941. def start(self, tag, attrs):
  942. self._flush()
  943. self._last = elem = self._factory(tag, attrs)
  944. if self._elem:
  945. self._elem[-1].append(elem)
  946. self._elem.append(elem)
  947. self._tail = 0
  948. return elem
  949. ##
  950. # Closes the current element.
  951. #
  952. # @param tag The element name.
  953. # @return The closed element.
  954. # @defreturn Element
  955. def end(self, tag):
  956. self._flush()
  957. self._last = self._elem.pop()
  958. assert self._last.tag == tag,\
  959. "end tag mismatch (expected %s, got %s)" % (
  960. self._last.tag, tag)
  961. self._tail = 1
  962. return self._last
  963. ##
  964. # Element structure builder for XML source data, based on the
  965. # <b>expat</b> parser.
  966. #
  967. # @keyparam target Target object. If omitted, the builder uses an
  968. # instance of the standard {@link #TreeBuilder} class.
  969. # @keyparam html Predefine HTML entities. This flag is not supported
  970. # by the current implementation.
  971. # @see #ElementTree
  972. # @see #TreeBuilder
  973. class XMLTreeBuilder:
  974. def __init__(self, html=0, target=None):
  975. try:
  976. from xml.parsers import expat
  977. except ImportError:
  978. raise ImportError(
  979. "No module named expat; use SimpleXMLTreeBuilder instead"
  980. )
  981. self._parser = parser = expat.ParserCreate(None, "}")
  982. if target is None:
  983. target = TreeBuilder()
  984. self._target = target
  985. self._names = {} # name memo cache
  986. # callbacks
  987. parser.DefaultHandlerExpand = self._default
  988. parser.StartElementHandler = self._start
  989. parser.EndElementHandler = self._end
  990. parser.CharacterDataHandler = self._data
  991. # let expat do the buffering, if supported
  992. try:
  993. self._parser.buffer_text = 1
  994. except AttributeError:
  995. pass
  996. # use new-style attribute handling, if supported
  997. try:
  998. self._parser.ordered_attributes = 1
  999. self._parser.specified_attributes = 1
  1000. parser.StartElementHandler = self._start_list
  1001. except AttributeError:
  1002. pass
  1003. encoding = None
  1004. if not parser.returns_unicode:
  1005. encoding = "utf-8"
  1006. # target.xml(encoding, None)
  1007. self._doctype = None
  1008. self.entity = {}
  1009. def _fixtext(self, text):
  1010. # convert text string to ascii, if possible
  1011. try:
  1012. return _encode(text, "ascii")
  1013. except UnicodeError:
  1014. return text
  1015. def _fixname(self, key):
  1016. # expand qname, and convert name string to ascii, if possible
  1017. try:
  1018. name = self._names[key]
  1019. except KeyError:
  1020. name = key
  1021. if "}" in name:
  1022. name = "{" + name
  1023. self._names[key] = name = self._fixtext(name)
  1024. return name
  1025. def _start(self, tag, attrib_in):
  1026. fixname = self._fixname
  1027. tag = fixname(tag)
  1028. attrib = {}
  1029. for key, value in attrib_in.items():
  1030. attrib[fixname(key)] = self._fixtext(value)
  1031. return self._target.start(tag, attrib)
  1032. def _start_list(self, tag, attrib_in):
  1033. fixname = self._fixname
  1034. tag = fixname(tag)
  1035. attrib = {}
  1036. if attrib_in:
  1037. for i in range(0, len(attrib_in), 2):
  1038. attrib[fixname(attrib_in[i])] = self._fixtext(attrib_in[i+1])
  1039. return self._target.start(tag, attrib)
  1040. def _data(self, text):
  1041. return self._target.data(self._fixtext(text))
  1042. def _end(self, tag):
  1043. return self._target.end(self._fixname(tag))
  1044. def _default(self, text):
  1045. prefix = text[:1]
  1046. if prefix == "&":
  1047. # deal with undefined entities
  1048. try:
  1049. self._target.data(self.entity[text[1:-1]])
  1050. except KeyError:
  1051. from xml.parsers import expat
  1052. raise expat.error(
  1053. "undefined entity %s: line %d, column %d" %
  1054. (text, self._parser.ErrorLineNumber,
  1055. self._parser.ErrorColumnNumber)
  1056. )
  1057. elif prefix == "<" and text[:9] == "<!DOCTYPE":
  1058. self._doctype = [] # inside a doctype declaration
  1059. elif self._doctype is not None:
  1060. # parse doctype contents
  1061. if prefix == ">":
  1062. self._doctype = None
  1063. return
  1064. text = string.strip(text)
  1065. if not text:
  1066. return
  1067. self._doctype.append(text)
  1068. n = len(self._doctype)
  1069. if n > 2:
  1070. type = self._doctype[1]
  1071. if type == "PUBLIC" and n == 4:
  1072. name, type, pubid, system = self._doctype
  1073. elif type == "SYSTEM" and n == 3:
  1074. name, type, system = self._doctype
  1075. pubid = None
  1076. else:
  1077. return
  1078. if pubid:
  1079. pubid = pubid[1:-1]
  1080. self.doctype(name, pubid, system[1:-1])
  1081. self._doctype = None
  1082. ##
  1083. # Handles a doctype declaration.
  1084. #
  1085. # @param name Doctype name.
  1086. # @param pubid Public identifier.
  1087. # @param system System identifier.
  1088. def doctype(self, name, pubid, system):
  1089. pass
  1090. ##
  1091. # Feeds data to the parser.
  1092. #
  1093. # @param data Encoded data.
  1094. def feed(self, data):
  1095. self._parser.Parse(data, 0)
  1096. ##
  1097. # Finishes feeding data to the parser.
  1098. #
  1099. # @return An element structure.
  1100. # @defreturn Element
  1101. def close(self):
  1102. self._parser.Parse("", 1) # end of data
  1103. tree = self._target.close()
  1104. del self._target, self._parser # get rid of circular references
  1105. return tree
  1106. # compatibility
  1107. XMLParser = XMLTreeBuilder