2011-11-01 40 views
7

Với đoạn mã sau ...NET Xml serializer thuộc tính tùy chọn

[XmlType("Field")] 
public class SearchField 
{ 
    [XmlAttribute("alias")] 
    public string Alias; 

    [XmlAttribute("entity")] 
    public string Entity; 
} 

Bí danh là một trường bắt buộc đối với chúng tôi, nhưng deserializer ném khi "bí danh" thuộc tính là mất tích từ xml. Làm thế nào để bạn làm cho nó tùy chọn? Lược đồ có cần thiết không?

Trả lời

9

Weird, vì chương trình sau hoạt động tốt đối với tôi, mà không cần bất kỳ throwings:

using System; 
using System.IO; 
using System.Xml; 
using System.Xml.Serialization; 

[XmlType("Field")] 
public class SearchField 
{ 
    [XmlAttribute("alias")] 
    public string Alias; 

    [XmlAttribute("entity")] 
    public string Entity; 
} 

class Program 
{ 
    static void Main() 
    { 
     using (var reader = new StringReader("<Field entity=\"en\" />")) 
     { 
      var serializer = new XmlSerializer(typeof(SearchField)); 
      var s = (SearchField)serializer.Deserialize(reader); 
      Console.WriteLine(s.Alias); 
      Console.WriteLine(s.Entity); 
     } 
    } 
} 

Như bạn có thể thấy các thuộc tính alias được bỏ qua từ XML đầu vào nhưng không có vấn đề deserializing.

Các vấn đề liên quan