2013-05-15 58 views
0
[XmlRoot("Class1")] 
class Class1 
{ 
[(XmlElement("Product")] 
public string Product{get;set;} 
[(XmlElement("Price")] 
public string Price{get;set;} 
} 

这是我的课。在这个价格中包含'£'符号。序列化到XML后,我得到'?'而不是'£'。XML中的类序列化

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

+0

向我们展示序列化代码。 –

+0

其实我有一个由其他团队开发的库。我们只使用该库,并获取序列化的XML。除了'英镑'符号,我得到的一切都很好。 – Bhushan

+0

听起来像编码的东西 - 输出是用UTF8编写的吗? –

回答

0

您的问题必须是如何将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; 
     } 
    } 

} 
+0

我相信你的回答是正确的。虽然XML可能会被序列化为UTF-8,但保存的文件是否编码为UTF-8?另外,如果没有BOM,Windows会尝试“猜测”编码,有时会出错。在Windows认为是ANSI或CP-1252的文件中使用UTF-8字符时,这非常明显 - 由于没有相应的字符,无效字符显示为“?”。只是有些想法可以帮助每个人。 – fourpastmidnight