我从Web服务中获取了一些XML。我建立了一些反序列化的类。它正在部分工作;我得到了任何SavingType
对象的原始成员的期望值。
正如代码所示,我得到了一个Saving
对象,该对象应该有多个,并且其字段为null。我在Savings
成员上有一些评论属性(也许我应该更改这些名称)。这些属性似乎应该比我在上面没有注释的XmlElement
更正确,但是当我使用它们时,反序列化对象的Savings
成员始终是一个空数组。我的错误在哪里?
<Product xmlns="http://schemas.datacontract.org/2004/07/mInitechService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
...
<AdvSaving>
<SavingType>...</SavingType>
<SavingType>...</SavingType>
<SavingType>
<Savings>
<Saving>
<apy>0.06</apy>
<dailyBalance>0.01</dailyBalance>
<divRate>0.06</divRate>
<name>Ultimate Checking </name>
</Saving>
<Saving>
<apy>0.10</apy>
<dailyBalance>10,000.00</dailyBalance>
<divRate>0.10</divRate>
<name>Ultimate Checking</name>
</Saving>
<Saving>
<apy>0.06</apy>
<dailyBalance>0.01</dailyBalance>
<divRate>0.06</divRate>
<name>Business Rewards Checking</name>
</Saving>
</Savings>
<savingNote>All rates are subject to change without prior notification. The APY figure assumes the principal and earned dividends remain on deposit until maturity. Fees may reduce earnings.

1 Must meet age requirements to participate.</savingNote>
<savingsMinBal>Minimum to open is $0.00</savingsMinBal>
<savingsTypeName>Checking</savingsTypeName>
</SavingType>
</AdvSaving>
<effectiveDate>Rates effective from 11/01/2018 through 11/30/2018</effectiveDate>
</Product>
和类:
namespace InitechServiceEntities
{
[XmlType(AnonymousType = true, Namespace = "http://schemas.datacontract.org/2004/07/mInitechService")]
[XmlRoot(Namespace = "http://schemas.datacontract.org/2004/07/mInitechService", IsNullable = false)]
public class Product
{
//...
[XmlArrayItem("SavingType", typeof(SavingType), IsNullable = false)]
public SavingType[] AdvSaving;
[XmlElement("effectiveDate")]
public string effectiveDate;
}
[XmlType("SavingType")]
public class SavingType
{
[XmlElement("savingsTypeName")]
public string savingsTypeName;
[XmlElement("savingsMinBal")]
public string savingsMinBal;
[XmlElement("savingNote")]
public string savingNote;
[XmlElement("Savings")]
//[XmlArray(ElementName = "Savings")]
//[XmlArrayItem(Type = typeof(Saving))]
public Saving[] Savings;
}
[XmlType("Saving")]
public class Saving
{
[XmlElement("name")]
public string name;
[XmlElement("dailyBalance")]
public decimal dailyBalance;
[XmlElement("divRate")]
public decimal divRate;
[XmlElement("apy")]
public decimal apy;
}
}
答案 0 :(得分:0)
您的数据模型有两个问题:
在SavingType
中,Savings
数组必须标记为[XmlArray("Savings")]
,以指示该集合已由外部容器元素<Savings>
和内部元素{ {1}}:
<Saving>
您最初是用这种方式标记数组的,然后将其注释掉并用[XmlArray(ElementName = "Savings")]
替换,这表明该集合应该在没有外部元素的情况下进行序列化-这不能反映实际的XML。
固定为#1,您将遇到第二个问题,即由于逗号的存在,// FIXED
[XmlArray("Savings")]
public Saving[] Savings;
的值10,000.00
无法解析为decimal ,因此反序列化期间会引发异常。
要解决此问题,您需要将<dailyBalance>10,000.00</dailyBalance>
更改为Saving.dailyBalance
,或引入一个代理属性来手动进行解析:
string
因此,修改后的固定类型如下:
// FIXED
[XmlElement("dailyBalance")]
public string dailyBalance;
提琴here。
顺便说一句,通过在内存中构造模型实例,然后序列化为XML,这些问题通常很容易诊断。当将生成的XML与要反序列化的XML进行比较时,结构上的任何差异都将表明反序列化代码在哪里存在bug。