# slixmpp.xmlstream.tostring# ~~~~~~~~~~~~~~~~~~~~~~~~~~# This module converts XML objects into Unicode strings and# intelligently includes namespaces only when necessary to# keep the output readable.# Part of Slixmpp: The Slick XMPP Library# :copyright: (c) 2011 Nathanael C. Fritz# :license: MIT, see LICENSE for more detailsfrom__future__importannotationsfromtypingimportOptional,Set,TYPE_CHECKINGfromxml.etree.ElementTreeimportElementifTYPE_CHECKING:fromslixmpp.xmlstreamimportXMLStreamXML_NS='http://www.w3.org/XML/1998/namespace'
[docs]deftostring(xml:Optional[Element]=None,xmlns:str='',stream:Optional[XMLStream]=None,outbuffer:str='',top_level:bool=False,open_only:bool=False,namespaces:Optional[Set[str]]=None)->str:"""Serialize an XML object to a Unicode string. If an outer xmlns is provided using ``xmlns``, then the current element's namespace will not be included if it matches the outer namespace. An exception is made for elements that have an attached stream, and appear at the stream root. :param XML xml: The XML object to serialize. :param string xmlns: Optional namespace of an element wrapping the XML object. :param stream: The XML stream that generated the XML object. :param string outbuffer: Optional buffer for storing serializations during recursive calls. :param bool top_level: Indicates that the element is the outermost element. :param set namespaces: Track which namespaces are in active use so that new ones can be declared when needed. :type xml: :py:class:`~xml.etree.ElementTree.Element` :type stream: :class:`~slixmpp.xmlstream.xmlstream.XMLStream` :rtype: Unicode string """ifxmlisNone:return''# Add previous results to the start of the output.output=[outbuffer]# Extract the element's tag name.tag_split=xml.tag.split('}',1)tag_name=tag_split[-1]# Extract the element's namespace if it is defined.if'}'inxml.tag:tag_xmlns=tag_split[0][1:]else:tag_xmlns=''default_ns=''stream_ns=''use_cdata=Falseifstream:default_ns=stream.default_nsstream_ns=stream.stream_nsuse_cdata=stream.use_cdata# Output the tag name and derived namespace of the element.namespace=''iftag_xmlns:iftop_levelandtag_xmlnsnotin[default_ns,xmlns,stream_ns] \
ornottop_levelandtag_xmlns!=xmlns:namespace=' xmlns="%s"'%tag_xmlnsifstreamandtag_xmlnsinstream.namespace_map:mapped_namespace=stream.namespace_map[tag_xmlns]ifmapped_namespace:tag_name="%s:%s"%(mapped_namespace,tag_name)output.append("<%s"%tag_name)output.append(namespace)# Output escaped attribute values.new_namespaces=set()forattrib,valueinxml.attrib.items():value=escape(value,use_cdata)if'}'notinattrib:output.append(' %s="%s"'%(attrib,value))else:attrib_split=attrib.split('}')attrib_ns=attrib_split[0][1:]attrib=attrib_split[1]ifattrib_ns==XML_NS:output.append(' xml:%s="%s"'%(attrib,value))elifstreamandattrib_nsinstream.namespace_map:mapped_ns=stream.namespace_map[attrib_ns]ifmapped_ns:ifnamespacesisNone:namespaces=set()ifattrib_nsnotinnamespaces:namespaces.add(attrib_ns)new_namespaces.add(attrib_ns)output.append(' xmlns:%s="%s"'%(mapped_ns,attrib_ns))output.append(' %s:%s="%s"'%(mapped_ns,attrib,value))ifopen_only:# Only output the opening tag, regardless of content.output.append(">")return''.join(output)iflen(xml)orxml.text:# If there are additional child elements to serialize.output.append(">")ifxml.text:output.append(escape(xml.text,use_cdata))iflen(xml):forchildinxml:output.append(tostring(child,tag_xmlns,stream,namespaces=namespaces))output.append("</%s>"%tag_name)elifxml.text:# If we only have text content.output.append(">%s</%s>"%(escape(xml.text,use_cdata),tag_name))else:# Empty element.output.append(" />")ifxml.tail:# If there is additional text after the element.output.append(escape(xml.tail,use_cdata))fornsinnew_namespaces:# Remove namespaces introduced in this context. This is necessary# because the namespaces object continues to be shared with other# contexts.ifnamespacesisnotNone:namespaces.remove(ns)return''.join(output)
defescape(text:str,use_cdata:bool=False)->str:"""Convert special characters in XML to escape sequences. :param string text: The XML text to convert. :rtype: Unicode string """escapes={'&':'&','<':'<','>':'>',"'":''','"':'"'}ifnotuse_cdata:return''.join(escapes.get(c,c)forcintext)else:escape_needed=Falseforcintext:ifcinescapes:escape_needed=Truebreakifescape_needed:escaped=map(lambdax:"<![CDATA[%s]]>"%x,text.split("]]>"))return"<![CDATA[]]]><![CDATA[]>]]>".join(escaped)returntextdef_get_highlight():try:frompygmentsimporthighlightfrompygments.lexersimportget_lexer_by_namefrompygments.formattersimportTerminal256FormatterLEXER=get_lexer_by_name('xml')FORMATTER=Terminal256Formatter()classHighlighter:__slots__=['string']def__init__(self,string):self.string=stringdef__str__(self):returnhighlight(str(self.string),LEXER,FORMATTER).strip()returnHighlighterexceptImportError:returnlambdax:xhighlight=_get_highlight()