.net XML serialization: how to specify the root element of an array and the names of child elements

Consider the following serializable classes:

class Item {...}
class Items : List<Item> {...}
class MyClass
{
   public string Name {get;set;}
   public Items MyItems {get;set;}
}

I want the serialized output to look like this:

<MyClass>
    <Name>string</Name>
    <ItemValues>
        <ItemValue></ItemValue>
        <ItemValue></ItemValue>
        <ItemValue></ItemValue>
    </ItemValues>
</MyClass>

Please note that the item names ItemValues ​​and ItemValue do not match the names of the Item and Items classes, if I cannot change the Item or Items class, are there any reasons for specifying the item names that I want by changing the MyClass class

+5
source share
3 answers
public class MyClass
{
    public string Name {get;set;}
    [XmlArray("ItemValues")]
    [XmlArrayItem("ItemValue")]
    public Items MyItems {get;set;}
}
+6
source

Maybe you should take a look at " How to specify an alternative element name for the XML stream "

XmlElementAttribute ElementName .

+1

Linq Xml XML . -

XElement element = new XElement(
    "MyClass",
    new XElement("Name", myClass.Name),
    new XElement(
        "ItemValues",
        from item in myClass.Items
        select new XElement(
            "ItemValue",
            new XElement("Foo", item.Foo))));

What will create

<MyClass>
  <Name>Blah</Name>
  <ItemValues>
    <ItemValue>
      <Foo>A</Foo>
    </ItemValue>
    <ItemValue>
      <Foo>B</Foo>
    </ItemValue>
  </ItemValues>
</MyClass>
0
source

All Articles