2013-06-14 12 views
5

Mam klasy zdefiniowane tak:C# Xml dlaczego mój atrybut nie pojawia się?

[XmlRoot(ElementName="request")] 
public class Request 
{ 
    #region Attributes 
    [XmlAttribute(AttributeName = "version")] 
    public string Version 
    { 
     get 
     { 
      return "1.0"; 
     } 
    } 

    [XmlAttribute(AttributeName = "action")] 
    public EAction Action 
    { 
     get; 
     set; 
    } 
    #endregion 

Ale kiedy szeregować je „wersja” nie pojawi się w atrybucie (podczas gdy „akcja” robi).

Co się dzieje źle?

Odpowiedz

4

XmlSerializer zamierza ignorować Version ponieważ nie posiada set, więc nie ma sposobu, może próbować nigdy Cofnięcie to. Może zamiast:

[XmlAttribute(AttributeName = "version")] 
public string Version {get;set;} 

public Request() { Version = "1.0"; } 

, które mają ten sam efekt ogólnie (choć wymaga dodatkowego string pole per przykład - chociaż wszystkie wartości "1.0" będą takie same rzeczywiste przykład string poprzez interning), lecz pozwoli Ci poprawnie przechwycić wersję danych, które są deserializujące.

Jeśli nie obchodzi o deserializacji, to może po prostu dodać no-op set:

[XmlAttribute(AttributeName = "version")] 
public string Version 
{ 
    get { return "1.0"; } 
    set { } 
} 
2

trzeba ustawić pustą setter. Jest to ograniczenie XmlAttribute.

[XmlRoot(ElementName="request")] 
public class Request 
{ 
    #region Attributes 
    [XmlAttribute(AttributeName = "version")] 
    public string Version 
    { 
     get 
     { 
      return "1.0"; 
     } 
     set{} 
    } 

    [XmlAttribute(AttributeName = "action")] 
    public EAction Action 
    { 
     get; 
     set; 
    } 
    #endregion 
Powiązane problemy