views:

261

answers:

3

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:

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

Notice the element names ItemValues and ItemValue doesn't match the class names Item and Items, assuming I can't change the Item or Items class, is there any why to specify the element names I want, by modifying the MyClass Class?

+1  A: 

You might want to look at "How to: Specify an Alternate Element Name for an XML Stream"

That article discusses using the XmlElementAttribute's ElementName to accomplish this.

statichippo
Please don't post .NET 1.1 links. Someone who clicks that link and doesn't notice will then click the links in the document, and be led to more and more old information.
John Saunders
Actually, `[XmlElement]` won't help here; that would allow you to do `<MyClass><Name>string</Name><ItemValue></ItemValue><ItemValue></ItemValue><ItemValue></ItemValue></MyClass>` (note no `<ItemValues>`), but not what the question asks.
Marc Gravell
+6  A: 
public class MyClass
{
    public string Name {get;set;}
    [XmlArray("ItemValues")]
    [XmlArrayItem("ItemValue")]
    public Items MyItems {get;set;}
}
Marc Gravell
A: 

You could also consider using Linq to Xml to construct your XML from your class. Something like

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))));

Which would create

<MyClass>
  <Name>Blah</Name>
  <ItemValues>
    <ItemValue>
      <Foo>A</Foo>
    </ItemValue>
    <ItemValue>
      <Foo>B</Foo>
    </ItemValue>
  </ItemValues>
</MyClass>
Anthony Pegram