Jeremy
Jeremy

Reputation: 46340

.net XML serialization: how to specify an array's root element and child element names

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?

Upvotes: 5

Views: 1113

Answers (3)

Anthony Pegram
Anthony Pegram

Reputation: 126814

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>

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062650

public class MyClass
{
    public string Name {get;set;}
    [XmlArray("ItemValues")]
    [XmlArrayItem("ItemValue")]
    public Items MyItems {get;set;}
}

Upvotes: 6

asbestossupply
asbestossupply

Reputation: 11909

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.

Upvotes: 1

Related Questions