Format potentially invalid XML I'm working on an application that allows users edit/fix XML.
A part of this is to format the XML for better readability.
As the XML might be invalid, the existing methods I found for formatting (like XmlWriter or XDocument) don't work for me.
There might be all sorts of problems with the XML, although the most common is unescaped special characters.
public static string FormatXml(string xml)
{
    var tags = xml
        .Split('&lt;')
        .Select(tag =&gt; tag.TrimEnd().EndsWith(&quot;&gt;&quot;) ? tag.TrimEnd() : tag); //Trim whitespace between tags, but not at the end of values

    var previousTag = tags.First(); //Preserve content before the first tag, e.g. if the initial &lt; is missing
    var formattedXml = new StringBuilder(previousTag);
    var indention = 0;
    
    foreach (var tag in tags.Skip(1))
    {
        if (previousTag.EndsWith(&quot;&gt;&quot;))
        {
            formattedXml.AppendLine();
            if (tag.StartsWith(&quot;/&quot;))
            {
                indention = Math.Max(indention - 1, 0);
                formattedXml.Append(new string('\t', indention));
            }
            else
            {
                formattedXml.Append(new string('\t', indention));
                if (!tag.EndsWith(&quot;/&gt;&quot;))
                {
                    indention++;
                }
            }
        }
        else
        {
            indention = Math.Max(indention - 1, 0);
        }

        formattedXml.Append(&quot;&lt;&quot;);
        formattedXml.Append(tag);
        previousTag = tag;
    }

    return formattedXml.ToString();
}

Sofar the method produces reasonable output for all cases I came up with.
I'm mostly worried that I missed some special cases of valid XML that would get messed up.
There's a test suite of 2000 test cases available at https://www.w3.org/XML/Test/ - try it out.
From a quick glance, it's not clear to me how you're handling content within comments or CDATA sections - which might be well-formed XML, or it might be something approximating to well-formed XML.
Another comment is that messing with whitespace is dangerous in mixed content. With inline markup (bold, italic etc) preserving whitespace as written may be important.