XML & Encoding

Come impostare l'attributo "Encoding" in un file XML...

using System.IO;
using System.Text;
using System.Xml.Linq;
namespace XMLEncoding
{
	public class XmlGenerator1
	{
		public string GenerateXml()
		{
			var document = new XDocument { Declaration = new XDeclaration("1.0", "UTF-8", "yes") };
			var message = new XElement("message");
			document.Add(message);
			
			var sb = new StringBuilder();
			using (var sw = new StringWriter(sb))
			{
				document.Save(sw);
			}

			return sb.ToString();
		}
	}

	public class XmlGeneratorUtf8
	{
		public string GenerateXml()
		{
			var document = new XDocument { Declaration = new XDeclaration("1.0", "UTF-8", "yes") };
			var message = new XElement("message");
			document.Add(message);
			
			var sb = new StringBuilder();
			
			using (var sw = new Utf8StringWriter(sb))
			{
				document.Save(sw);
			}
			
			return sb.ToString();
		}
	}

	public class Utf8StringWriter : StringWriter
	{
		public Utf8StringWriter(StringBuilder sb) : base(sb) { }
		public override Encoding Encoding{get { return Encoding.UTF8; }	}
	}
}

Risultato:

XmlGenerator1 xmlgenerator1 = new XmlGenerator1();
string s = xmlgenerator1.GenerateXml();
//<? xml version = "1.0" encoding = "utf-16" standalone = "yes" ?>
//< message />

XmlGeneratorUtf8 xmlgeneratorUtf8 = new XmlGeneratorUtf8();
string sUtf8 = xmlgenerator1.GenerateXml();
//<? xml version = "1.0" encoding = "utf-16" standalone = "yes" ?>
//< message /> 
Add a Comment