2

I want to serialize a List<AbstractClass> that contains DerivedClassA and DerivedClassB where both of these classes are derived from AbstractClass.

Additionally I want to add an attribute to the element that wraps each element of the list. My desired output is something like this:

<MyCustomListName foo="bar">
    <DerivedClassA baseAttribute="value" attributeFromA="value"/>
    <DerivedClassB baseAttribute="value" attributeFromB="value"/>
    ...
</MyCustomListName> 

What I have so far is this:

public class MyCustomListName
{
   [XmlAttribute]
   public string foo {get; set;}

   [XmlArray]        
   public List<AbstractClass> list { get; set; }

}

[XmlInclude(typeof(DerivedClassA))]
[XmlInclude(typeof(DerivedClassB))]
public abstract class AbstractClass
{
   [XmlAttribute]
   public string baseAttribute {get; set;}
}

public class DerivedClassA : AbstractClass
{
   [XmlAttribute]
   public string attributeFromA {get; set;}
}

public class DerivedClassB : AbstractClass
{
   [XmlAttribute]
   public string attributeFromB {get; set;}
}

Using this, I get the following output:

<MyCustomListName foo="bar">
  <list>
    <AbstractClass xsi:type="DerivedClassA" baseAttribute="value" attributeFromA="value"/>
    <AbstractClass xsi:type="DerivedClassB" baseAttribute="value" attributeFromB="value"/>
  </list>
</MyCustomListName>

So, to get my desired output, there should be no nested <list> element and instead of the xsi:type attribute, the element name should be DerivedClassA or DerivedClassB depending on the type.

1 Answer 1

3

Provide different names for items of different types:

[XmlElement("derivedA", typeof(DerivedClassA))]
[XmlElement("derivedB", typeof(DerivedClassB))]
public List<AbstractClass> list { get; set; }
Sign up to request clarification or add additional context in comments.

1 Comment

This seems to work for creating the proper element names. However, I would need to not output the <list> tag.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.