How to change encoding in TextWriter object?
18,598
Solution 1
This seems odd, but it looks like you have to subclass StringWriter
if you want to output to a string
with utf-8 encoding in the xml.
public class Program
{
public static void Main(string[] args)
{
XDocument xDoc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Entity",new XAttribute("Type", "attribute1")));
StringBuilder builder = new StringBuilder();
using (TextWriter writer = new EncodingStringWriter(builder, Encoding.UTF8))
{
xDoc.Save(writer);
}
Console.WriteLine(builder.ToString());
}
}
public class EncodingStringWriter : StringWriter
{
private readonly Encoding _encoding;
public EncodingStringWriter(StringBuilder builder, Encoding encoding) : base(builder)
{
_encoding = encoding;
}
public override Encoding Encoding
{
get { return _encoding; }
}
}
Solution 2
Try
TextWriter ws = new StreamWriter(path, true, Encoding.UTF8);
or
TextWriter ws = new StreamWriter(stream, Encoding.UTF8);
Author by
user1848942
Updated on June 12, 2022Comments
-
user1848942 12 months
I have xml which I send by API in another resurse. I create it by XDocument:
XDocument xDoc = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XElement("Entity",new XAttribute("Type", "attribute1"), new XElement("Fields",...
When I put it in the request it has sent without declaration. So I do next:
StringBuilder builder = new StringBuilder(); TextWriter writer = new StringWriter(builder); using (writer) { xDoc.Save(writer); }
But now TextWriter change encoding in xml to utf-16. I need to change it again on utf-8.
-
BlueChippy over 10 yearsor
Encoding.GetEncoding(1256)
if you need a specific code page (1256 is Arabic) -
Nyerguds over 8 years
StreamWriter
seems like the obvious solution, yes; it is, after all, the specific encoding-customizable implementation ofTextWriter
, the type expected byXDocument.Save
. Even for just going back to String (but getting the XML declaration right) I just use this, on aMemoryStream
.