如何使用XmlAttributeOverrides覆盖集合元素的xml元素名称?

我有一个非常基本的对象对象模型,由System.Xml.XmlSerialization东西序列化。 我需要使用XmlAttributeOverridesfunction为子元素集合设置xml元素名称。

public class Foo{ public List Bars {get; set; } } public class Bar { public string Widget {get; set; } } 

使用标准的xml序列化程序,这将成为

    ...   

我需要使用XmlOverrideAttributes来说明这一点

    ...   

但我似乎无法让它重命名集合中的子元素…我可以重命名集合本身…我可以重命名根…不知道我做错了什么。

这是我现在的代码:

 XmlAttributeOverrides xOver = new XmlAttributeOverrides(); var bars = new XmlElementAttribute("SomethingElse", typeof(Bar)); var elementNames = new XmlAttributes(); elementNames.XmlElements.Add(bars); xOver.Add(typeof(List), "Bars", elementNames); StringBuilder stringBuilder = new StringBuilder(); StringWriter writer = new StringWriter(stringBuilder); XmlSerializer serializer = new XmlSerializer(typeof(Foo), xOver); serializer.Serialize(writer, someFooInstance); string xml = stringBuilder.ToString(); 

但这根本不会改变元素的名称……我做错了什么?

谢谢

要做到这一点,你需要[XmlArray][XmlArrayItem] (理想情况下两者都要明确):

 using System.Collections.Generic; using System.IO; using System.Xml.Serialization; public class Foo { public List Bars { get; set; } } public class Bar { public string Widget { get; set; } } static class Program { static void Main() { XmlAttributeOverrides xOver = new XmlAttributeOverrides(); xOver.Add(typeof(Foo), "Bars", new XmlAttributes { XmlArray = new XmlArrayAttribute("Bars"), XmlArrayItems = { new XmlArrayItemAttribute("SomethingElse", typeof(Bar)) } }); XmlSerializer serializer = new XmlSerializer(typeof(Foo), xOver); using (var writer = new StringWriter()) { Foo foo = new Foo { Bars = new List { new Bar { Widget = "widget"} }}; serializer.Serialize(writer, foo); string xml = writer.ToString(); } } } 

德里克,

这对我有用 – 不确定它是否适合你:

 public class Foo { [XmlArrayItem(ElementName = "SomethingElse")] public List Bars { get; set; } }