April 6, 2010

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Create a XML Tree from a String"
 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions