두 항목이 포함 된 개체 목록이 있습니다. 각 개체에는 여러 속성이 포함되어 있습니다. 내 문제는 두 항목을 모두 xml로 직렬화해야하지만 두 요소에 대해 다른 속성을 사용해야한다는 것입니다.
이미 XmlAttributeOverrides를 시도했습니다.
예제 클래스 :
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public class Apple
{
[System.Xml.Serialization.XmlElementAttribute(DataType="nonNegativeInteger")]
public int Index{ get; set;}
[System.Xml.Serialization.XmlAttributeAttribute()]
public int Size{ get; set;}
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal Weight{ get; set;}
}
void Test()
{
List<Apple> apples = new List<Apple>
{
new Apple {Index = 0, Size = 1},
new Apple {Index = 1, Weight = 4}
};
}
직렬화 후 결과 :
& ltApple Size = 1> <Index & gt0 </ Index> </ Apple> & ltApple Weight = 4> <Index & gt1 </ Index> </ Apple>
이것은 "조건부 직렬화"처럼 보입니다. 여기서는 Nullable<T>
"값이 있습니까?"에 대한 저장소로 사용 하고 있으며, public bool ShouldSerialize*()
수행 할 작업을 결정하기 위해 많은 serializer에서 패턴을 인식합니다.
private int? _size;
[XmlAttribute]
public int Size
{
get => _size.GetValueOrDefault();
set => _size = value;
}
public bool ShouldSerializeSize() => _size.HasValue;
private decimal? _weight;
[XmlAttribute]
public decimal Weight
{
get => _weight.GetValueOrDefault();
set => _weight = value;
}
public bool ShouldSerializeWeight() => _weight.HasValue;
이를 통해 직렬 변환기는 기본적으로 다음을 수행합니다 (의사 코드).
if (obj.ShouldSerializeSize()) output.WriteAttribute("Size", obj.Size);
if (obj.ShouldSerializeWeight()) output.WriteAttribute("Weight", obj.Weight);
"양수인 경우에만 직렬화"와 같은 다른 규칙을 사용할 수도 있습니다.
[XmlAttribute]
public int Size {get;set;}
public bool ShouldSerializeSize() => Size > 0;
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다