c#xml序列化,包含unicodes

时间:2015-08-18 04:36:45

标签: c# xml serialization unicode

C#中的对象序列化自动序列化html标签和&迹象。 但我有一个字符串,其值如下所示,没有转换为xml / html safe。

•TEST1•TEST2•TEST3 15°C 36°F

请注意我的示例字符串中有两个特殊字符。一个是子弹,另一个是温度符号。

将对象序列化为xml的代码非常流行。这可能有什么问题?

    public static String ToXmlString(this Object obj)
    {
        var objectType = obj.GetType();
        XmlSerializer serializer = new XmlSerializer(objectType);
        StringBuilder xml = new StringBuilder();
        using (Utf8StringWriter writer = new Utf8StringWriter(xml))
        {
            serializer.Serialize(writer, obj);
        }
        return xml.ToString();
    }

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

1 个答案:

答案 0 :(得分:0)

我使用过XmlDocument而不是XmlSerialzier

public static String ToXmlString(this Object xmlObj)
        {
            var objectType = xmlObj.GetType();
            var document = new XmlDocument();
            document.LoadXml(xml: xmlObj.ToString());
            StringBuilder xmldata = new StringBuilder();
            var ele = (XmlElement)document.FirstChild;
            foreach(var item in document)
            {
                xmldata.Append(item);
            }
            Console.WriteLine(ele.InnerXml); 
            return xmldata.ToString();
        }