Return pretty formatted XML.
199291
def pformat_xml(xml):
    """"""
    try:
        from lxml import etree  # delayed import
        if not isinstance(xml, bytes):
            xml = xml.encode('utf-8')
        xml = etree.parse(io.BytesIO(xml))
        xml = etree.tostring(xml, pretty_print=True, xml_declaration=True,
                             encoding=xml.docinfo.encoding)
        xml = bytes2str(xml)
    except Exception:
        if isinstance(xml, bytes):
            xml = bytes2str(xml)
        xml = xml.replace('><', '>\n<')
    return xml.replace('  ', ' ').replace('\t', ' ')
348399
def Element(cls, s, *args):
        """"""
        sargs = []
        for arg in args:
            if type(arg) == etree._Element:
                sargs.append(etree.tounicode(arg))
            else:
                sargs.append(arg)
        if type(s) == etree._Element:
            t = etree.tounicode(s)
        else:
            t = s
        if len(args) == 0:
            return XML.fromstring(t)
        else:
            return XML.fromstring(t % tuple(sargs))
605218
public static function format($xml) {
        $domtree = new DOMDocument('1.0', 'UTF-8');
        $domtree->loadXML($xml);
        $domtree->preserveWhiteSpace = false;
        $domtree->formatOutput = true;
        $domtree->setIndent = (1);
        return $domtree->saveXML();
    }
1149405
def looks_like_xml(text):
    """"""
    if xml_decl_re.match(text):
        return True
    key = hash(text)
    try:
        return _looks_like_xml_cache[key]
    except KeyError:
        m = doctype_lookup_re.match(text)
        if m is not None:
            return True
        rv = tag_re.search(text[:1000]) is not None
        _looks_like_xml_cache[key] = rv
        return rv
138613
def pretty_str(self, indent=0):
        
        return '{}{} {} = {}'.format(' ' * indent, self.result, self.name,
                                     pretty_str(self.value))
900273
def as_text(self, is_pretty=False):
        """"""
        values = {'id': self._id, 'type': self._type}
        if self._owner:
            values['owner'] = self._owner

        if is_pretty:
            return json.dumps(values, indent=4, separators=(',', ': '))

        return json.dumps(values)
415708
def prettyXml(elem):
    
    roughString = ET.tostring(elem, "utf-8")
    reparsed = minidom.parseString(roughString)
    return reparsed.toprettyxml(indent="  ")
241364
def toxml(self):
        

        return '<Record quantity="{0}" scale="{1}" color="{2}" id="{3}"/>'.format(self.quantity,
                                                                         self.scale,
                                                                         self.color,
                                                                         self.id)
512973
def beautify_xml(path):
    
    with open(path) as f:
        content = f.read()

    pretty_print = lambda data: '\n'.join([line for line in
                                           parseString(data)
                                           .toprettyxml(indent=' ' * 2)
                                           .split('\n')
                                           if line.strip()])
    return pretty_print(content)
475018
public static String formatXml(String xml) {
    assertInitialization();
    return XLog.sLogConfiguration.xmlFormatter.format(xml);
  }
844737
def xmltreefromfile(filename):
    """"""
    try:
        return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))
    except TypeError:
        return ElementTree.parse(filename, ElementTree.XMLParser())
732756
def raw(request):
    """"""
    foos = foobar_models.Foo.objects.all()
    return HttpResponse(tree.xml(foos), mimetype='text/xml')
1058466
def prettyfy(response, format='json'):
    
    if format == 'json':
        return pretty_json(response.content)
    else:
        return pretty_xml(response.content)
420265
def prettify_xml(elem):
    
    from xml.dom import minidom
    import xml.etree.cElementTree as et

    rough_string = et.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="  ")
962082
def xml(self, attribs = None,elements = None, skipchildren = False):
        """"""
        E = ElementMaker(namespace=NSFOLIA,nsmap={None: NSFOLIA, 'xml' : "http://www.w3.org/XML/1998/namespace"})

        if not attribs: attribs = {}
        if not elements: elements = []

        if self.id:
            attribs['id'] = self.id
            try:
                w = self.doc[self.id]
                attribs['t'] = w.text()
            except KeyError:
                pass

        e  = makeelement(E, '{' + NSFOLIA + '}' + self.XMLTAG, **attribs)
        return e
1304581
def _get_pretty_body(headers, body):
    
    try:
        if CONTENT_TYPE_HEADER_NAME in headers:
            if XMLRenderer.DEFAULT_CONTENT_TYPE == headers[CONTENT_TYPE_HEADER_NAME]:
                xml_parsed = parseString(body)
                pretty_xml_as_string = xml_parsed.toprettyxml()
                return pretty_xml_as_string
            elif JSONRenderer.DEFAULT_CONTENT_TYPE == headers[CONTENT_TYPE_HEADER_NAME]:
                decoded_body = body.decode('utf-8')
                parsed = json.loads(decoded_body)
                return json.dumps(parsed, sort_keys=True, indent=4)
    except:
        pass
    finally:
        return body
1363815
def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ):
        
        nl = "\n"
        out = []
        namedItems = dict((v[1],k) for (k,vlist) in self.__tokdict.items()
                                                            for v in vlist)
        nextLevelIndent = indent + "  "

        # collapse out indents if formatting is not desired
        if not formatted:
            indent = ""
            nextLevelIndent = ""
            nl = ""

        selfTag = None
        if doctag is not None:
            selfTag = doctag
        else:
            if self.__name:
                selfTag = self.__name

        if not selfTag:
            if namedItemsOnly:
                return ""
            else:
                selfTag = "ITEM"

        out += [ nl, indent, "<", selfTag, ">" ]

        for i,res in enumerate(self.__toklist):
            if isinstance(res,ParseResults):
                if i in namedItems:
                    out += [ res.asXML(namedItems[i],
                                        namedItemsOnly and doctag is None,
                                        nextLevelIndent,
                                        formatted)]
                else:
                    out += [ res.asXML(None,
                                        namedItemsOnly and doctag is None,
                                        nextLevelIndent,
                                        formatted)]
            else:
                # individual token, see if there is a name for it
                resTag = None
                if i in namedItems:
                    resTag = namedItems[i]
                if not resTag:
                    if namedItemsOnly:
                        continue
                    else:
                        resTag = "ITEM"
                xmlBodyText = _xml_escape(_ustr(res))
                out += [ nl, nextLevelIndent, "<", resTag, ">",
                                                xmlBodyText,
                                                "</", resTag, ">" ]

        out += [ nl, indent, "</", selfTag, ">" ]
        return "".join(out)