XmlSerializer에서 Null 값 형식을 내 보내지 못하도록합니다.
nullable XmlElement로 표시된 다음 Amount 값 유형 속성을 고려하십시오.
[XmlElement(IsNullable=true)]
public double? Amount { get ; set ; }
nullable 값 형식이 null로 설정된 경우 C # XmlSerializer 결과는 다음과 같습니다.
<amount xsi:nil="true" />
이 요소를 내보내는 대신 XmlSerializer가 요소를 완전히 억제하기를 원합니다. 왜? 온라인 결제에 Authorize.NET을 사용하고 있으며이 null 요소가 있으면 Authorize.NET은 요청을 거부합니다.
현재 솔루션 / 해결 방법은 Amount 값 유형 속성을 전혀 직렬화하지 않는 것입니다. 대신 Amount를 기반으로하고 대신 직렬화되는 보완 속성 SerializableAmount를 만들었습니다. SerializableAmount는 참조 형식과 마찬가지로 기본적으로 null 인 경우 XmlSerializer에 의해 억제되는 String 형식이므로 모든 것이 잘 작동합니다.
/// <summary>
/// Gets or sets the amount.
/// </summary>
[XmlIgnore]
public double? Amount { get; set; }
/// <summary>
/// Gets or sets the amount for serialization purposes only.
/// This had to be done because setting value types to null
/// does not prevent them from being included when a class
/// is being serialized. When a nullable value type is set
/// to null, such as with the Amount property, the result
/// looks like: >amount xsi:nil="true" /< which will
/// cause the Authorize.NET to reject the request. Strings
/// when set to null will be removed as they are a
/// reference type.
/// </summary>
[XmlElement("amount", IsNullable = false)]
public string SerializableAmount
{
get { return this.Amount == null ? null : this.Amount.ToString(); }
set { this.Amount = Convert.ToDouble(value); }
}
물론 이것은 해결 방법 일뿐입니다. null 값 형식 요소가 방출되지 않도록 억제하는 더 깨끗한 방법이 있습니까?
추가해보십시오 :
public bool ShouldSerializeAmount() {
return Amount != null;
}
프레임 워크의 일부에서 인식되는 여러 패턴이 있습니다. 정보를 원하시면, XmlSerializer또한 찾습니다 public bool AmountSpecified {get;set;}.
전체 예 (로 전환 decimal) :
using System;
using System.Xml.Serialization;
public class Data {
public decimal? Amount { get; set; }
public bool ShouldSerializeAmount() {
return Amount != null;
}
static void Main() {
Data d = new Data();
XmlSerializer ser = new XmlSerializer(d.GetType());
ser.Serialize(Console.Out, d);
Console.WriteLine();
Console.WriteLine();
d.Amount = 123.45M;
ser.Serialize(Console.Out, d);
}
}
MSDN의 ShouldSerialize *에 대한 자세한 정보 .
얻을 수있는 대안도 있습니다
<amount /> instead of <amount xsi:nil="true" />
사용하다
[XmlElement("amount", IsNullable = false)]
public string SerializableAmount
{
get { return this.Amount == null ? "" : this.Amount.ToString(); }
set { this.Amount = Convert.ToDouble(value); }
}
당신은 이것을 시도 할 수 있습니다 :
xml.Replace("xsi:nil=\"true\"", string.Empty);
'Program Club' 카테고리의 다른 글
| C ++에서 std :: vector를 반환하는 효율적인 방법 (0) | 2020.11.23 |
|---|---|
| JAXB : XML 문서를 비 정렬 화하는 동안 네임 스페이스를 무시하는 방법은 무엇입니까? (0) | 2020.11.23 |
| 자바 스크립트를 사용하여 키 코드를 문자로 변환하는 방법 (0) | 2020.11.23 |
| 돌아 가기 대신 "이동"버튼이있는 iOS 키보드 (0) | 2020.11.23 |
| java.io.IOException : 표시 / 재설정이 지원되지 않음 (0) | 2020.11.23 |