Format potentially invalid XML
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.