tostring.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. # -*- coding: utf-8 -*-
  2. """
  3. sleekxmpp.xmlstream.tostring
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. This module converts XML objects into Unicode strings and
  6. intelligently includes namespaces only when necessary to
  7. keep the output readable.
  8. Part of SleekXMPP: The Sleek XMPP Library
  9. :copyright: (c) 2011 Nathanael C. Fritz
  10. :license: MIT, see LICENSE for more details
  11. """
  12. from __future__ import unicode_literals
  13. import sys
  14. if sys.version_info < (3, 0):
  15. import types
  16. XML_NS = 'http://www.w3.org/XML/1998/namespace'
  17. def tostring(xml=None, xmlns='', stream=None, outbuffer='',
  18. top_level=False, open_only=False, namespaces=None):
  19. """Serialize an XML object to a Unicode string.
  20. If an outer xmlns is provided using ``xmlns``, then the current element's
  21. namespace will not be included if it matches the outer namespace. An
  22. exception is made for elements that have an attached stream, and appear
  23. at the stream root.
  24. :param XML xml: The XML object to serialize.
  25. :param string xmlns: Optional namespace of an element wrapping the XML
  26. object.
  27. :param stream: The XML stream that generated the XML object.
  28. :param string outbuffer: Optional buffer for storing serializations
  29. during recursive calls.
  30. :param bool top_level: Indicates that the element is the outermost
  31. element.
  32. :param set namespaces: Track which namespaces are in active use so
  33. that new ones can be declared when needed.
  34. :type xml: :py:class:`~xml.etree.ElementTree.Element`
  35. :type stream: :class:`~sleekxmpp.xmlstream.xmlstream.XMLStream`
  36. :rtype: Unicode string
  37. """
  38. # Add previous results to the start of the output.
  39. output = [outbuffer]
  40. # Extract the element's tag name.
  41. tag_name = xml.tag.split('}', 1)[-1]
  42. # Extract the element's namespace if it is defined.
  43. if '}' in xml.tag:
  44. tag_xmlns = xml.tag.split('}', 1)[0][1:]
  45. else:
  46. tag_xmlns = ''
  47. default_ns = ''
  48. stream_ns = ''
  49. use_cdata = False
  50. if stream:
  51. default_ns = stream.default_ns
  52. stream_ns = stream.stream_ns
  53. use_cdata = stream.use_cdata
  54. # Output the tag name and derived namespace of the element.
  55. namespace = ''
  56. if tag_xmlns:
  57. if top_level and tag_xmlns not in [default_ns, xmlns, stream_ns] \
  58. or not top_level and tag_xmlns != xmlns:
  59. namespace = ' xmlns="%s"' % tag_xmlns
  60. if stream and tag_xmlns in stream.namespace_map:
  61. mapped_namespace = stream.namespace_map[tag_xmlns]
  62. if mapped_namespace:
  63. tag_name = "%s:%s" % (mapped_namespace, tag_name)
  64. output.append("<%s" % tag_name)
  65. output.append(namespace)
  66. # Output escaped attribute values.
  67. new_namespaces = set()
  68. for attrib, value in xml.attrib.items():
  69. value = escape(value, use_cdata)
  70. if '}' not in attrib:
  71. output.append(' %s="%s"' % (attrib, value))
  72. else:
  73. attrib_ns = attrib.split('}')[0][1:]
  74. attrib = attrib.split('}')[1]
  75. if attrib_ns == XML_NS:
  76. output.append(' xml:%s="%s"' % (attrib, value))
  77. elif stream and attrib_ns in stream.namespace_map:
  78. mapped_ns = stream.namespace_map[attrib_ns]
  79. if mapped_ns:
  80. if namespaces is None:
  81. namespaces = set()
  82. if attrib_ns not in namespaces:
  83. namespaces.add(attrib_ns)
  84. new_namespaces.add(attrib_ns)
  85. output.append(' xmlns:%s="%s"' % (
  86. mapped_ns, attrib_ns))
  87. output.append(' %s:%s="%s"' % (
  88. mapped_ns, attrib, value))
  89. if open_only:
  90. # Only output the opening tag, regardless of content.
  91. output.append(">")
  92. return ''.join(output)
  93. if len(xml) or xml.text:
  94. # If there are additional child elements to serialize.
  95. output.append(">")
  96. if xml.text:
  97. output.append(escape(xml.text, use_cdata))
  98. if len(xml):
  99. for child in xml:
  100. output.append(tostring(child, tag_xmlns, stream,
  101. namespaces=namespaces))
  102. output.append("</%s>" % tag_name)
  103. elif xml.text:
  104. # If we only have text content.
  105. output.append(">%s</%s>" % (escape(xml.text, use_cdata), tag_name))
  106. else:
  107. # Empty element.
  108. output.append(" />")
  109. if xml.tail:
  110. # If there is additional text after the element.
  111. output.append(escape(xml.tail, use_cdata))
  112. for ns in new_namespaces:
  113. # Remove namespaces introduced in this context. This is necessary
  114. # because the namespaces object continues to be shared with other
  115. # contexts.
  116. namespaces.remove(ns)
  117. return ''.join(output)
  118. def escape(text, use_cdata=False):
  119. """Convert special characters in XML to escape sequences.
  120. :param string text: The XML text to convert.
  121. :rtype: Unicode string
  122. """
  123. if sys.version_info < (3, 0):
  124. if type(text) != types.UnicodeType:
  125. text = unicode(text, 'utf-8', 'ignore')
  126. escapes = {'&': '&amp;',
  127. '<': '&lt;',
  128. '>': '&gt;',
  129. "'": '&apos;',
  130. '"': '&quot;'}
  131. if not use_cdata:
  132. text = list(text)
  133. for i, c in enumerate(text):
  134. text[i] = escapes.get(c, c)
  135. return ''.join(text)
  136. else:
  137. escape_needed = False
  138. for c in text:
  139. if c in escapes:
  140. escape_needed = True
  141. break
  142. if escape_needed:
  143. escaped = map(lambda x : "<![CDATA[%s]]>" % x, text.split("]]>"))
  144. return "<![CDATA[]]]><![CDATA[]>]]>".join(escaped)
  145. return text