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

问题描述 投票:0回答:2

我有一个问题从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元素,但没有任何东西。

c# .net web-services wcf deserialization
2个回答
0
投票

你应该使用[XmlArrayItem]属性:

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

0
投票

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

    [DataMember(Name = "Countries", IsRequired = false)]
    [XmlArray("Countries")]
    [XmlArrayItem("Country")]
    public List<Country> Countries { get; set; }
© www.soinside.com 2019 - 2024. All rights reserved.