2017-04-23 6 views
-4

선택할 수있는 방법은 어떤 일이두 개의 서로 다른 속성

[System.Xml.Serialization.XmlElement(ElementName= "DealId")] 
[System.Xml.Serialization.XmlIgnore] 
public int ID { get; set; } 

처럼 내가 하나 개의 요소를 선택할 실행 시간 동안하고 싶은. 어떻게 할 수 있습니까?

답변

2

XmlAttributeOverrides 클래스를 사용하면 런타임에 속성을 동적으로 재정의 할 수 있습니다. 다음은 그 예이다 : 다음

public class MyModel 
{ 
    public int ID { get; set; } 
} 

및 직렬화 때 우리는 우리의 모델의 ID 속성이 XmlElementAttribute 또는 XmlIgnoreAttribute있을 것이다 중 하나를 지정 런타임에 몇 가지 조건에 따라이 예에서

var attributeOverrides = new XmlAttributeOverrides(); 
var attributes = new XmlAttributes(); 
if (SomeCondition()) 
{ 
    attributes.XmlIgnore = true; 
} 
else 
{ 
    attributes.XmlElements.Add(new XmlElementAttribute("DealId")); 
} 

attributeOverrides.Add(typeof(MyModel), "ID", attributes); 

// when instantiating the XmlSerializer we specify the attribute overrides 
var serializer = new XmlSerializer(typeof(MyModel), attributeOverrides); 
var model = new MyModel 
{ 
    ID = 5, 
}; 

serializer.Serialize(Console.Out, model); 

.

+0

고맙습니다. 작동 원리 –

1

선택적으로 Id 필드를 직렬화하려는 것 같습니다.

그러나,이 같은 같은 클래스에 메소드를 정의 할 수 있습니다 :

public bool ShouldSerializeID() 
{ 
    return !string.IsNullOrWhiteSpace(this.ID); 
} 

다음은 [XmlIgnore] 속성을 제거합니다. 이 예제에서 ID는 값이있는 곳에서 직렬화됩니다.

관련 문제