XDocument xDocumentObject = XDocument.Parse("<Test>"+
"<elementx id='1' att='aaa' />" +
"<elementx id='2' att='bbb' />" +
"</Test>");
What is the difference between :
1)
byte[] xmlBytes = Encoding.Default.GetBytes(xDocumentObject.ToString());
AND
2)
byte[] xmlBytes;
using (MemoryStream ms = new MemoryStream())
{
xDocumentObject.Save(ms);
xmlBytes = ms.ToArray();
}
What is “Default” encoding in (1) and what is the encoding used in (2) and which is the preferred way?
In the first case you are using the encoding for the operating system’s current ANSI code page to convert the string to a byte array. The string represents the XML document generated by the
XDocumentinstance and converted to a byte array. In .NET all strings are Unicode encoded.In the second example the encoding of the XDocument is used. So for example if you have the following XML
<?xml encoding="utf-8"?>it will use UTF-8. The Declaration property allows you to specify the encoding being used:or:
allows you to specify UTF-8 encoding.