简体   繁体   中英

Xml Array Deserialization to C# object without top level arrayElement

I have the following Xml :

<Head>
<Name>someName</Name>
<Config>
  <Section name='One'/>  
  <Section name='Two'/>
</Config>
</Head>

and I would like it to map the following object structure:

public class Head{
   public String Name {get;set;}

   public Config Config {get;set;}       

}

public class Config
{       
    public Section[] Sections { get; set; }
}

public class Section
{
    [XmlAttribute(AttributeName="name")]
    public String Name { get; set; }

}

How can I do this using Attributes only (if possible?) but without adding a top level < Sections > above < Section > elements, and also keeping the class structure. I have tried with XmlArrayItem, but i can't get the section elements.

Before asking the questions, I've tried the XmlArrayAttribute and the XmlArraItemAttribute with all possible combinations of namedProperty, and the attribute to be used was simply XmlElement . So I managed it like this:

just added the [XmlElement(ElementName="Section")] on top of the Sections property in the Config class. updated here below :

  public class Head{
     public String Name {get;set;}

     public Config Config {get;set;}       

  }

  public class Config
  {       
      [XmlElement(ElementName="Section")]
      public Section[] Sections { get; set; }
  }

  public class Section
  {
      [XmlAttribute(AttributeName="name")]
      public String Name { get; set; }

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM