我有一个问题从SQL Server反序列化XML。 XML很好;反序列化的代码是已知的工作代码;但由于某种原因,它只是反序列化第一级和第二级,这意味着类与XML不匹配,但在盯着它后我无法识别它。
这是XML的摘录:
<Options>
<Countries>
<Country ID="1" Name="Afghanistan" Code="AF" ISO="4" SubDivision="City" PostalName="Postal Code" />
<Country ID="2" Name="Albania" Code="AL" ISO="8" SubDivision="City" PostalName="Postal Code" />
<Country ID="3" Name="Algeria" Code="DZ" ISO="12" SubDivision="City" PostalName="Postal Code" />
<Country ID="4" Name="American Samoa" Code="AS" ISO="16" SubDivision="City" PostalName="Postal Code" />
<Country ID="5" Name="Andorra" Code="AD" ISO="20" SubDivision="City" PostalName="Postal Code" />
</Countries>
<EntityTypes>
<EntityType ID="4" Name="Individual" />
<EntityType ID="5" Name="Business" />
</EntityTypes>
</Options>
这是Options
类:
namespace RecoverItWCF.Classes
{
[DataContract]
[Serializable()]
public class Options
{
[DataMember(Name = "Categories", IsRequired = false)]
[XmlElement("Categories")]
public Category[] Categories;
[DataMember(Name = "Countries", IsRequired = false)]
[XmlElement("Countries")]
public Country[] Countries;
[DataMember(Name = "EntityTypes", IsRequired = false)]
[XmlElement("EntityTypes")]
public EntityType[] EntityTypes;
}
}
这是Country
类:
namespace RecoverItWCF.Classes
{
[DataContract]
[Serializable()]
public class Country
{
[DataMember(Name = "ID", IsRequired = true)]
[XmlAttribute("ID")]
public string ID { get; set; }
[DataMember(Name = "Name", IsRequired = true)]
[XmlAttribute("Name")]
public string Name { get; set; }
// truncated for brevity
}
}
这是EntityType
类:
namespace RecoverItWCF.Classes
{
[DataContract]
[Serializable()]
public class EntityType
{
[DataMember(Name = "ID")]
[XmlAttribute("ID")]
public Int16 ID { get; set; }
[DataMember(Name = "Name")]
[XmlAttribute("Name")]
public string Name { get; set; }
}
}
Options
元素不包含Categories
元素(正确),并且包含Countries
元素(正确),但Countries
级别在断点处突出显示时没有任何东西(没有Country
数组),并且它应该有200个Country
元素。它还包含一个EntityTypes
元素,但没有任何东西。
你应该使用[XmlArrayItem]
属性:
[XmlArrayItem("Countries", IsNullable=true, Type = typeof(Country))]
public Country[] Countries;
感谢@ Xiaoy312带领我走正路。需要对Options类进行更正。这完成了工作。
[DataMember(Name = "Countries", IsRequired = false)]
[XmlArray("Countries")]
[XmlArrayItem("Country")]
public List<Country> Countries { get; set; }