DiskJunky DiskJunky - 3 months ago 21
C# Question

Xml Serialize root attribute on List class

I have a piece of XML that I need to serialize/deserialize but I'm having a lot of difficulty in getting it to work exactly as needed. The code I have works for 98% of the structure but I'm unable to get attributes serialized/deserialized on the root node.

Sample XML;

<rootNode date="2000-01-01" time="07:00">
<detail>
<reference>12345</reference>
</detail>
</rootNode>


Classes currently being used to deserialize to;

[XmlType("detail")]
public class Detail
{
[XmlElement("reference")]
public string Reference { get; set; }
}

[XmlRoot("rootNode")]
public class Root : List<Detail>
{
[XmlAttribute("date")]
public string Date { get; set; }

[XmlAttribute("time")]
public string Time { get; set; }
}


The specifics of each element being renamed from the actual XML is important and necessary in my implementation. If I don't inherit from
List<Detail>
and have a collection property (assume
Details
of same type) then I can get the attributes but end up with XML like;

<rootNode date="2000-01-01" time="07:00">
<Details>
<detail>
<reference>12345</reference>
</detail>
</Details>
</rootNode>


But that isn't what I'm trying to deserialize. Controlling the way it's serialized via
XmlArray
and
XmlArrayItem
allows me to rename the collection node and the item nodes but not get rid of the collection node itself. Any suggestions?

Answer

I think you should remove inheritance from Root to List, and add the Details attribute to Root:

[XmlType("detail")]
public class Detail
{
    [XmlElement("reference")]
    public string Reference { get; set; }
}

[XmlRoot("rootNode")]
public class Root
{
    [XmlAttribute("date")]
    public string Date { get; set; }

    [XmlAttribute("time")]
    public string Time { get; set; }

    [XmlElement("detail")]
    List<Detail> Details  { get; set; }

}
Comments