3

The following model class serializes to

    [XmlRoot]
    public class A
    {
        [XmlAttribute]
        public string Period { get; set; }

        public List<C> B { get; set; }

    }

<?xml version=1.0>
<A Period="Today">
 <B>
    <C>
    </C>
    <C>
    </C>
  </B>
</A>

Now, I dont want that <B> (List of objects should directly be listed under XmlRoot)

The resulting XML should look like,

<A Period="Today">
  <C>
  </C>
  <C>
  </C>
</A>

Any ideas how ?

1 Answers1

5

Set the list as an XML element. This will force the rendering of only its elements:

[XmlRoot]
public class A
{
    [XmlAttribute]
    public string Period { get; set; }

    [XmlElement("C")]
    public List<C> B { get; set; }

}
Andrei V
  • 7,306
  • 6
  • 44
  • 64
  • This still gives me C node under B node. I don't want B node at all. – now he who must not be named. Jun 11 '14 at 08:09
  • 1
    @nowhewhomustnotbenamed., I read your question wrong the first time. Updated. – Andrei V Jun 11 '14 at 08:10
  • Just curious: Can you tell me from where did you read or know this ? Any references to further dig in to this info please.. – now he who must not be named. Jun 11 '14 at 09:18
  • 1
    @nowhewhomustnotbenamed., I've recently had the same problem, that's why I remembered it. I've searched for question that solved the problem: http://stackoverflow.com/questions/2006482/c-sharp-xml-serialization-disable-rendering-root-element-of-array. Check out the attributes listed here: http://msdn.microsoft.com/en-us/library/System.Xml.Serialization(v=vs.110).aspx. It might come in handy next time. :) – Andrei V Jun 11 '14 at 10:01