Wednesday, 24 April 2013

How to convert an XML document into String in C#?

How to convert an XML document into String in C#?
Sometimes we come into the need where we have an XML file and we have to save that file in form of C# string. Well, converting XML document in string in C# is very easy. I will use XDocument class to do this job. With following steps you can easily do this with few lines of code in C#?
Step 1: Include namespace System.Xml.Linq.
using System.Xml.Linq;
Step 2: Load XML file in XDocument using following line of C# code.
var xDocument = XDocument.Load(@"C:\MyXMLFilePath.xml");
Step 3: Convert the xml into string
string xml = xDocument.ToString();
Now you can use this xml string wherever required.


  1. I tried your coding. The coding can be compiled successfully but where can I get the string file after compiling?

  2. Sorry, I found that there is an error when debugging. The error is the "Data at the root level is invalid". Why does this error appear?