matteeyah
matteeyah

Reputation: 875

.NET XML Serializer - Array Custom Attributes

I'm totally stumped as to how can I achieve XML structure such as this:

<sizes type=”1”>
    <size status=”1”>L</size>
    <size status=”1”>XL</size>
   <size status=”0”>XXL</size>
<sizes>

I am able to create such structure:

<sizes>
    <size>L</size>
    <size>XL</size>
   <size>XXL</size>
<sizes>

With XmlArray and XmlArrayItem attributes.

[XmlArray(ElementName = "sizes")]
[XmlArrayItem(ElementName = "size")]

But what I'm unable to do is to add those custom attributes. How do I go about doing that? Do I have to create a new object that'll hold those values and set a custom attribute for it?

Upvotes: 1

Views: 250

Answers (1)

Volkan Paksoy
Volkan Paksoy

Reputation: 6937

You should define them as attributes. This should work:

using System.Collections.Generic;
using System.Xml.Serialization;

public class sizes
{
    [XmlAttribute("type")]
    public string type { get; set; }

    [XmlElement("size")]
    public List<size> sizeList { get; set; }
}

public class size
{
    [XmlAttribute("status")]
    public string status { get; set; }
}

and the code to deserialize:

string xml = File.ReadAllText("XMLFile1.xml");
XmlSerializer ser = new XmlSerializer(typeof(sizes));
var sizes = ser.Deserialize(new StringReader(xml));

Upvotes: 1

Related Questions