开发者

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

开发者 https://www.devze.com 2022-12-23 06:30 出处:网络
Consider the following serializable classes: class Item {...} class Items : List<Item> {...} class MyClass

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>
0

精彩评论

暂无评论...
验证码 换一张
取 消