To convert xml string to XNode in C# and VB.NET you can use the snippet below.

Sample C#

public static XNode XmlStringToXNode(string xmlInputString)
{
	if (String.IsNullOrEmpty(xmlInputString.Trim())) { throw new ArgumentNullException("xmlInputString"); }
	using (var stringReader = new StringReader(xmlInputString))
	{
		using (var xmlReader = XmlReader.Create(stringReader))
		{
			xmlReader.Read();
			return XNode.ReadFrom(xmlReader);
		}
	}
}

Sample VB.NET

Public Shared Function XmlStringToXNode(xmlInputString As String) As XNode
	If String.IsNullOrEmpty(xmlInputString.Trim()) Then
		Throw New ArgumentNullException("xmlInputString")
	End If
	Using stringReader = New StringReader(xmlInputString)
		Using xmlReader__1 = XmlReader.Create(stringReader)
			xmlReader__1.Read()
			Return XNode.ReadFrom(xmlReader__1)
		End Using
	End Using
End Function

3 thought on “How to convert xml string to XNode in C# and VB.NET”

Leave a Reply