简体   繁体   English

使用UTF8编码在C#中创建XML

[英]Creating XML in C# with UTF8 encoding

I know that there is a lot of tutorials about this and even answered questions here, but I have problem I'm trying to resolve for hours and I read almost everything here, but this still remains mistery for me. 我知道这里有很多教程,甚至在这里回答了问题,但是我有一个问题试图解决几个小时,而且我在这里几乎阅读了所有内容,但是这仍然对我来说是迷茫的。 Please help: 请帮忙:

I'm creating XML, and it's created, but the problem is that encoding is UTF-16, and it should be UTF-8. 我正在创建XML,并且已经创建了XML,但是问题是编码是UTF-16,应该是UTF-8。 This is what I tried so far, but still is UTF-16: 这是我到目前为止尝试过的,但仍然是UTF-16:

        var xmlText = new StringBuilder();

        using (var xml = XmlWriter.Create(xmlText))
        {
            xml.WriteStartDocument();
            xml.WriteStartElement("Weather");


            if (model.ModuleList[0] != null)
            {
                foreach (var weather in model.ModuleList)
                {
                    var AddProperty = new Action<XmlWriter, ModuleModel>((a, forc) =>
                    {
                        xml.WriteStartElement("Forecast");
                        a.WriteElementString("Description", forc.Description);
                        a.WriteElementString("Date", forc.Date.ToString());
                        a.WriteElementString("MinTemp", forc.Min_Temp.ToString());
                        a.WriteElementString("MaxTemp", forc.Max_Temp.ToString());
                        a.WriteElementString("Pressure", forc.Pressure.ToString());
                        a.WriteElementString("Humidity", forc.Humidity.ToString());                           
                        xml.WriteEndElement();
                    });
                    AddProperty(xml, weather);
                }
            }             

            xml.WriteEndElement();
            xml.WriteEndDocument();
        }
        var xmlresult = xmlText.ToString();

How to set encoding to my XML to UTF-8? 如何将我的XML的编码设置为UTF-8? Please help... 请帮忙...

The result of your code is a string xmlresult - and strings do not have an encoding, they are always Unicode. 您的代码的结果是字符串xmlresult字符串没有编码,它们始终是Unicode。

You use an encoding when you convert a string to a sequence of byte - so your problem is not in the piece of code you posted, but in the code you use to write that string to a file. 在将字符串转换为字节序列时会使用编码-因此,问题不在于发布的代码段,而在于用于将该字符串写入文件的代码。

Something like this: 像这样:

 using (StreamWriter writer = new StreamWriter(fileName, true, Encoding.UTF8))
 {
     writer.Write(xmlresult);
 }

will write a UTF-8 file - where filename contains the path of the file. 将写入一个UTF-8文件-其中filename包含filename的路径。

If you need UTF-8 encoded bytes in memory use: 如果需要在内存中使用UTF-8编码的字节,请使用:

var utf8Bytes = Encoding.UTF8.GetBytes("xmlresult");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM