1

I am trying to figure out a way to specify the element name for serialization when I inherit from List

class 
{
    [XmlRoot(ElementName = "Foo")]
    public class Widget
    {
        public int ID { get; set; }
    }

    [XmlRoot(ElementName = "Foos")]
    public class WidgetList : List<Widget>
    {

    }
}

public static XElement GetXElement(object obj)
{
    using (var memoryStream = new MemoryStream())
    {
        using (TextWriter streamWriter = new StreamWriter(memoryStream))
        {
            var xmlSerializer = new XmlSerializer(obj.GetType());
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("dn", "http://defaultnamespace");
            xmlSerializer.Serialize(streamWriter, obj, ns);
            return XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));
        }
    }
}

static void Main(string[] args)
{

    WidgetList list = new WidgetList();

    list.Add(new Widget { ID = 0 });
    list.Add(new Widget { ID = 1 });

    XElement listElement = GetXElement(list);

    Console.WriteLine(listElement.ToString());
    Console.ReadKey();
}

Result:

<Foos xmlns:dn="http://defaultnamespace">
  <Widget>
    <ID>0</ID>
  </Widget>
  <Widget>
    <ID>1</ID>
  </Widget>
</Foos>

Desired Result:

<Foos xmlns:dn="http://defaultnamespace">
  <Foo>
    <ID>0</ID>
  </Foo>
  <Foo>
    <ID>1</ID>
  </Foo>
</Foos>

I was mostly wondering if I could modify "GetXElement" to respect the XmlRoot attribute of "Widget", but I am open to other ideas as long as I can still inherit from list. I do not like the solution given here: Serialize a generic collection specifying element names for items in the collection

Community
  • 1
  • 1
Matthew Bierman
  • 360
  • 3
  • 12

1 Answers1

1
[XmlType(TypeName = "Foo")]
[Serializable]
public class Widget
{
    public int ID { get; set; }
}
osos95
  • 169
  • 1
  • 10