The following code is used to process and write XML in the memory:Code:
Private string serializedata ()
{
Stringbuilder sb = new stringbuilder ();
Xmlwritersettings settings = new xmlwritersettings ();
Settings. Encoding = encoding. utf8; // Why is there no effect?
Settings. indent = true;
Using (xmlwriter writer = xmlwriter. Create (SB, settings ))
{
Xmlserializer serializer =
New xmlserializer (typeof (myclass ));
Serializer. serialize (writer, aninstanceofmyclass );
Writer. Flush ();
Writer. Close ();
}
Return sb. tostring ();
}
However, no matter how you set it in settings, the properties of the UTF-16 are output
<? XML version = "1.0" encoding ="UTF-16"?>
<Myclass xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: XSD = "http://www.w3.org/2001/XMLSchema" generatedat = "03:28:26">
...
Original
. Net strings are always UTF-16, And so stringbuilder always builds a UTF-16 string. so in that case you cannot override the encoding. if you want an in memory array of encoded bytes then use new streamwriter (New memorystream () then get the buffer from the memorystream.
Many Solutions
The simplest method is to replace the XML generated by stringbuilder.
XML. Replace ("UTF-16", "UTF-8 ");
Or
Use stream instead of stringbuilder:
Private string serializedata ()
{
String XML;
Using ( Memorystream MS = new memorystream ())
{
Streamwriter Sw = new streamwriter (MS );
Xmlwritersettings settings = new xmlwritersettings ();
Settings. Encoding = encoding. utf8;
Settings. indent = true;
Using (xmlwriter writer = xmlwriter. Create (SW, settings ))
{
Xmlserializer serializer = new xmlserializer (typeof (myclass ));
Serializer. serialize (writer, aninstanceofmyclass );
Writer. Flush ();
Writer. Close ();
}
Using (streamreader sr = new streamreader (MS ))
{
Ms. Position = 0;
Xml = Sr. readtoend ();
Sr. Close ();
}
}
Return XML;
}
This method seems a bit cool
In addition, when using xmlwriter, use writeprocessinginstruction to explicitly specify the xml header
Using (xmlwriter writer = xmlwriter. Create (OBJ ))
{
Writer. writeprocessinginstruction ("XML", "version = \" 1.0 \ "encoding = \" UTF-8 \ "standalone = \" Yes \"");
Writer. writestartelement ("root ");
Writer. writestartelement ("example_element ");
Writer. writeendelement ();
Writer. writeendelement ();
Writer. Flush ();
}