在.net服务中将XML反序列化为自定义嵌套类

时间:2016-05-11 01:58:03

标签: c# .net web-services wcf deserialization

我遇到了从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元素,但不包含任何内容。

2 个答案:

答案 0 :(得分:0)

您应该使用[XmlArrayItem]属性:

[XmlArrayItem("Countries", IsNullable=true, Type = typeof(Country))]
public Country[] Countries;

答案 1 :(得分:0)

感谢@ Xiaoy312带领我走正确的道路。需要对Options类进行更正。这完成了工作。

    [DataMember(Name = "Countries", IsRequired = false)]
    [XmlArray("Countries")]
    [XmlArrayItem("Country")]
    public List<Country> Countries { get; set; }