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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) 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 is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: