如何序列化UTF 8 xml字符串

时间:2018-03-30 14:51:33

标签: c# xml encoding xml-serialization xmlserializer

我有这个代码来创建一个xml。它曾经按预期工作,但在第一个xml行中,编码设置为utf-16。

代码是:

s=df.set_index(['item','timePoint']).value.unstack().stack(dropna=False)
s.groupby(level=0).ffill().reset_index()
Out[508]: 
    item  timePoint    0
0      1          1  2.0
1      1          2  2.0
2      1          3  4.0
3      2          1  4.0
4      2          2  4.0
5      2          3  5.0
6      3          1  7.0
7      3          2  5.0
8      3          3  3.0
9      4          1  6.0
10     4          2  9.0
11     4          3  9.0
12     5          1  NaN
13     5          2  3.0
14     5          3  3.0
15     6          1  NaN
16     6          2  2.0
17     6          3  2.0
18     7          1  NaN
19     7          2  NaN
20     7          3  1.0

由于我需要用UTF-8编码,我按如下方式编辑它:

public static string SerializeObject<T>(this T toSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());

    using (StringWriter textWriter = new StringWriter())
    {
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}

代码似乎很好,但生成的xml仍然是行

public static string SerializeObject<T>(this T toSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());


    XmlWriterSettings settings = new XmlWriterSettings()
    {
        Encoding = new  UTF8Encoding(),
        Indent = false,
        OmitXmlDeclaration = false
    };

    using (StringWriter textWriter = new StringWriter())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
        {
            xmlSerializer.Serialize(xmlWriter, toSerialize);
        }
        return textWriter.ToString();
    }
}

而不是

<?xml version="1.0" encoding="utf-16"?>

为什么呢?如何创建utf-8 xml?

0 个答案:

没有答案