.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 modify开发者_StackOverflow社区ing the MyClass Class?
public class MyClass
{
public string Name {get;set;}
[XmlArray("ItemValues")]
[XmlArrayItem("ItemValue")]
public Items MyItems {get;set;}
}
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.
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>
精彩评论