简体   繁体   English

.net XML序列化:如何指定数组的根元素和子元素名称

[英].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? 请注意,元素名称ItemValues和ItemValue与类名称Item和Items不匹配,假设我无法更改Item或Items类,是否有任何原因通过修改MyClass类来指定我想要的元素名称?

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 " 您可能希望查看“ 如何:为XML流指定备用元素名称

That article discusses using the XmlElementAttribute 's ElementName to accomplish this. 该文章讨论了使用XmlElementAttributeElementName来实现这一目的。

You could also consider using Linq to Xml to construct your XML from your class. 您还可以考虑使用Linq to Xml从您的类构建XML。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM