Menus

Tuesday, December 4, 2012

Create a XML Tree from a String

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
There is an easy way to do so. We 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

No comments:

Post a Comment