How to get XNode as Xml String with indentation in C# and VB.NET

Sample C#

public static String XNodeToString(XNode node, int indentation = 2)
{
	using (var sw = new StringWriter())
	{
		using (var xw = new XmlTextWriter(sw))
		{
			xw.Formatting = Formatting.Indented;
			xw.Indentation = indentation;
			node.WriteTo(xw);
		}
		return sw.ToString();
	}
}

Sample VB.NET

Public Shared Function XNodeToString(node As XNode, Optional indentation As Integer = 2) As String
	Using sw = New StringWriter()
		Using xw = New XmlTextWriter(sw)
			xw.Formatting = Formatting.Indented
			xw.Indentation = indentation
			node.WriteTo(xw)
		End Using
		Return sw.ToString()
	End Using
End Function

for more informations on indentation = 2 see XmlTextWriter.Indentation Property

Please Share us:
Please rate this snippet

4 thoughts on “How to get XNode as Xml String with indentation in C# and VB.NET

Leave a Reply