Can I specify the element name of the items when I inherit f

本文关键字:the inherit when items name specify element Can of | 更新日期: 2023-09-27 18:26:43

当我从List继承时,我正试图找到一种方法来指定要序列化的元素名称

class 
{
    [XmlRoot(ElementName = "Foo")]
    public class Widget
    {
        public int ID { get; set; }
    }
    [XmlRoot(ElementName = "Foos")]
    public class WidgetList : List<Widget>
    {
    }
}
public static XElement GetXElement(object obj)
{
    using (var memoryStream = new MemoryStream())
    {
        using (TextWriter streamWriter = new StreamWriter(memoryStream))
        {
            var xmlSerializer = new XmlSerializer(obj.GetType());
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("dn", "http://defaultnamespace");
            xmlSerializer.Serialize(streamWriter, obj, ns);
            return XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));
        }
    }
}
static void Main(string[] args)
{
    WidgetList list = new WidgetList();
    list.Add(new Widget { ID = 0 });
    list.Add(new Widget { ID = 1 });
    XElement listElement = GetXElement(list);
    Console.WriteLine(listElement.ToString());
    Console.ReadKey();
}

结果:

<Foos xmlns:dn="http://defaultnamespace">
  <Widget>
    <ID>0</ID>
  </Widget>
  <Widget>
    <ID>1</ID>
  </Widget>
</Foos>

期望结果:

<Foos xmlns:dn="http://defaultnamespace">
  <Foo>
    <ID>0</ID>
  </Foo>
  <Foo>
    <ID>1</ID>
  </Foo>
</Foos>

我主要想知道我是否可以修改"GetXElement"以尊重"Widget"的XmlRoot属性,但我对其他想法持开放态度,只要我仍然可以从列表继承。我不喜欢这里给出的解决方案:序列化一个通用集合,为集合中的项指定元素名称

Can I specify the element name of the items when I inherit f

[XmlType(TypeName = "Foo")]
[Serializable]
public class Widget
{
    public int ID { get; set; }
}