Last active
March 11, 2020 20:16
-
-
Save c272/816e5ea8c8956f75aa34db089e265cc4 to your computer and use it in GitHub Desktop.
Returns a pretty print string of a given XML string, with escape characters added in for invalid chars.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// <summary> | |
| /// Formats a given string into pretty print XML. | |
| /// </summary> | |
| private string FormatXml(string xml) | |
| { | |
| try | |
| { | |
| XDocument doc = XDocument.Parse(xml); | |
| //Get the string representation out. | |
| string indentedXml = doc.ToString(); | |
| var xmlBuilder = new StringBuilder(indentedXml); | |
| //Try to format the Regex strings. | |
| var matches = Regex.Matches(indentedXml, "<string>[^\r\n]*</string>"); | |
| foreach (Match match in matches) | |
| { | |
| //Get the string out, XML format it. | |
| string regex = match.Value.Replace("<string>", "").Replace("</string>", ""); | |
| regex = SecurityElement.Escape(regex); | |
| regex = "<string>" + regex + "</string>"; | |
| xmlBuilder.Remove(match.Index, match.Length); | |
| xmlBuilder.Insert(match.Index, regex); | |
| } | |
| //Return the XML. | |
| return xmlBuilder.ToString(); | |
| } | |
| catch (Exception e) | |
| { | |
| //Failed, just return normal XML. | |
| Error.Compile("Failed to generate valid Textmate file: '" + e.Message + "'."); | |
| return null; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment