Create a XML Tree from a String

I got a mail from a devcurry.com reader Martin this morning who asks me “I have a string containing XML tags and I need to create a XML document out of it without much efforts. Is there an easy way to do so. I can assure that the string contains valid xml

Yes Martin, there is an easy way to do so. You have to use the XDocument.Parse() method. Here’s an example. Add a reference to System.Xml.Linq and write the following code in a console application

C#

static void Main(string[] args)
{
string str = @"<?xml version=""1.0""?>
<Country name=""India"">
<Capital>New Delhi</Capital>
</Country>"
;
// preserve whitespaces
XDocument xDoc = XDocument.Parse(str, LoadOptions.PreserveWhitespace);
Console.WriteLine(xDoc);
Console.ReadLine();
}

VB.NET

Sub Main(ByVal args() As String)
Dim s As String = "<?xml version=""1.0""?>" & ControlChars.CrLf & _
" <Country name=""India"">" & ControlChars.CrLf & _
" <Capital>New Delhi</Capital>" & ControlChars.CrLf & " </Country>"
' preserve whitespaces
Dim xDoc As XDocument = XDocument.Parse(s, LoadOptions.PreserveWhitespace)
Console.WriteLine(xDoc)
Console.ReadLine()
End Sub

OUTPUT

XML document from string






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: