I know this is not really an answer to the question, but based on the number of votes for the question and the accepted answer, I suspect the people are actually using the code to serialize an object to a string.
Using XML serialization adds unnecessary extra text rubbish to the output.
For the following class
public class UserData{ public int UserId { get; set; }}
it generates
<?xml version="1.0" encoding="utf-16"?><UserData xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><UserId>0</UserId></UserData>
Better solution is to use JSON serialization (one of the best is Json.NET).To serialize an object:
var userData = new UserData {UserId = 0};var userDataString = JsonConvert.SerializeObject(userData);
To deserialize an object:
var userData = JsonConvert.DeserializeObject<UserData>(userDataString);
The serialized JSON string would look like:
{"UserId":0}