|
Formatting XML String
Published: 12/29/2008 |
|
I wrote a handy little routine for a client that takes an unformatted string of XML and formats it using indents to make it more human-readable. it's a single routine that accepts a string (assuming that it contains valid XML) and returns a string containing the same XML formatted with indents. Here it is, for your enjoyment:
VB:
Protected Function FormatXML(ByVal XML As String) As String
Dim lastReturn As Boolean = True
Dim temp As StringBuilder = New StringBuilder()
' break content into lines based on xml element tags...
For i As Integer = 0 To XML.Length - 1
If XML.Chars(i) = "<"c Then
If (Not lastReturn) Then
temp.Append(System.Environment.NewLine)
End If
End If
If XML.Chars(i) = ">"c Then
temp.AppendLine(XML.Chars(i).ToString())
lastReturn = True
Else
temp.Append(XML.Chars(i))
lastReturn = False
End If
Next i
' process indentation...
Dim indent As String = ""
Dim indentChars As String = " "
Dim ret As StringBuilder = New StringBuilder()
Dim lines As String() = temp.ToString().Split(New String() { System.Environment.NewLine }, StringSplitOptions.None)
For i As Integer = 0 To lines.Length - 1
If i > 0 Then
If lines(i - 1).EndsWith("?>") OrElse lines(i - 1).EndsWith("/>") OrElse lines(i - 1).StartsWith("</") Then
' outdent if a tag terminator...
If lines(i).StartsWith("</") Then
indent = indent.Substring(indentChars.Length)
End If
Else
If lines(i).StartsWith("</") Then
' outdent...
indent = indent.Substring(indentChars.Length)
Else
' indent...
indent &= indentChars
End If
End If
' prepend indent to line...
ret.Append(indent)
End If
' append line to output...
ret.AppendLine(lines(i))
Next i
' return...
Return ret.ToString()
End Function
protected string FormatXML(string XML)
{
bool lastReturn = true;
StringBuilder temp = new StringBuilder();
// break content into lines based on xml element tags...
for (int i = 0; i < XML.Length; i++)
{
if (XML[i] == '<')
{
if (!lastReturn) temp.Append(System.Environment.NewLine);
}
if (XML[i] == '>')
{
temp.AppendLine(XML[i].ToString());
lastReturn =
true;
}
else
{
temp.Append(XML[i]);
lastReturn =
false;
}
}
// process indentation...
string indent = "";
string indentChars = " ";
StringBuilder ret = new StringBuilder();
string[] lines = temp.ToString().Split(new string[] { "\r\n" }, StringSplitOptions.None);
for (int i = 0; i < lines.Length; i++)
{
if (i > 0)
{
if (lines[i - 1].EndsWith("?>") || lines[i - 1].EndsWith("/>") || lines[i - 1].StartsWith("</"))
{
// outdent if a tag terminator...
if (lines[i].StartsWith("</"))
indent = indent.Substring(indentChars.Length);
}
else
{
if (lines[i].StartsWith("</"))
{
// outdent...
indent = indent.Substring(indentChars.Length);
}
else
{
// indent...
indent += indentChars;
}
}
// prepend indent to line...
ret.Append(indent);
}
// append line to output...
ret.AppendLine(lines[i]);
}
// return...
return ret.ToString();
}
Questions or Comments? .
VB to C# and C# to VB translation provided by Instant C# and Instant VB.