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
Tweet
No comments:
Post a Comment