Skip to content

Instantly share code, notes, and snippets.

@c272
Last active March 11, 2020 20:16
Show Gist options
  • Select an option

  • Save c272/816e5ea8c8956f75aa34db089e265cc4 to your computer and use it in GitHub Desktop.

Select an option

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.
/// <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