XML中的类序列化

本文关键字:序列化 XML | 更新日期: 2023-09-27 18:13:45

[XmlRoot("Class1")]
class Class1
{
[(XmlElement("Product")]
public string Product{get;set;}
[(XmlElement("Price")]
public string Price{get;set;}
}
这是我的班。这里的价格包含"£"符号。在将其序列化为XML后,我得到'?’而不是‘£’。

我需要做什么才能在XML中获得'£' ?或者我如何将价格中的数据作为CDATA传递?

XML中的类序列化

您的问题必须与如何将XML写入文件有关。

我已经编写了一个程序,它使用了到目前为止您给我的信息,当我打印出XML字符串时,它是正确的。

我得出的结论是,错误要么发生在将数据写入XML文件时,要么发生在从XML文件中读取数据时。

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            new Program().Run();
        }
        void Run()
        {
            Class1 test = new Class1();
            test.Product = "Product";
            test.Price = "£100";
            Test(test);
        }
        void Test<T>(T obj)
        {
            XmlSerializerNamespaces Xsn = new XmlSerializerNamespaces();
            Xsn.Add("", ""); 
            XmlSerializer submit = new XmlSerializer(typeof(T)); 
            StringWriter stringWriter = new StringWriter(); 
            XmlWriter writer = XmlWriter.Create(stringWriter); 
            submit.Serialize(writer, obj, Xsn); 
            var xml = stringWriter.ToString(); // Your xml This is the serialization code. In this Obj is the object to serialize
            Console.WriteLine(xml);  // £ sign is fine in this output.
        }
    }
    [XmlRoot("Class1")]
    public class Class1
    {
        [XmlElement("Product")]
        public string Product
        {
            get;
            set;
        }
        [XmlElement("Price")]
        public string Price
        {
            get;
            set;
        }
    }
}
相关文章: