我尝试反序列化这个xml:
<AccountInfo ID="accid1" Currency="EUR">
<AccountNumber international="false">10000</AccountNumber>
<AccountNumber international="true">DE10000</AccountNumber>
<BankCode international="false">22222</BankCode>
<BankCode international="true">BC22222</BankCode>
<AccountHolder>Some Dude</AccountHolder>
</AccountInfo>
进入下面的课程:
public class AccountInfo
{
public int ID {get; set;}
public string Currency {get; set;}
public long AccountNumber {get; set;} //this should be filled if international == false
public string BankCode {get; set;}
public long AccountNumberInternational {get; set;} //this should be filled if internation == true
public string BankCodeInternational {get; set;}
public string AccountHolder {get; set;}
}
但我坚持认为如何告诉Deserializer(System.Xml.Serialization,.NET 4.6.1)填写类的属性AccountNumber / BankCode,具体取决于来自AccountNumber / BankCode的属性“international” XML。
到目前为止,我尝试使用这个“序列化”类:
[XmlRoot("AccountInfo")]
public class AccountInfo
{
[XmlAttribute]
public int ID { get; set; }
[XmlAttribute]
public string Currency { get; set; }
[XmlElement]
public BankAccount BankAccount { get; set; }
public string AccountHolder { get; set; }
}
public class BankAccount
{
public long AccountNumber { get; set; }
public int BankCode { get; set; }
}
但这甚至不会导致我需要的结构。
我如何声明序列化的类?
答案 0 :(得分:3)
XmlSerializer
旨在将数据反序列化为基本与XML形状相同的DTO模型,如下所示:
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
static class Program
{
static void Main()
{
var xml = @"<AccountInfo ID=""accid1"" Currency=""EUR"">
<AccountNumber international=""false"">10000</AccountNumber>
<AccountNumber international=""true"">DE10000</AccountNumber>
<BankCode international=""false"">22222</BankCode>
<BankCode international=""true"">BC22222</BankCode>
<AccountHolder>Some Dude</AccountHolder>
</AccountInfo>";
var ser = new XmlSerializer(typeof(AccountInfo));
var obj = ser.Deserialize(new StringReader(xml));
// ...
}
}
public class AccountInfo
{
[XmlElement]
public List<BankAccount> AccountNumber { get; } = new List<BankAccount>();
[XmlElement]
public List<BankAccount> BankCode { get; } = new List<BankAccount>();
public string AccountHolder { get; set; }
[XmlAttribute("ID")]
public string Id {get;set;}
[XmlAttribute]
public string Currency {get;set;}
}
public class BankAccount
{
[XmlAttribute("international")]
public bool International { get; set; }
[XmlText]
public string Number { get; set; }
}
您希望选择并推送到域模型中的哪些值应由后完成 - 例如,仅选择国际或非国际列表中的项目。