我有一个非常基本的对象对象模型,由System.Xml.XmlSerialization东西序列化。我需要使用XmlAttributeOverrides功能为子元素集合设置xml元素名称。
public class Foo{
public List Bars {get; set; }
}
public class Bar {
public string Widget {get; set; }
}
使用标准的xml序列化程序,这将显示为
<Foo>
<Bars>
<Bar>...</Bar>
</Bars>
</Foo>
我需要使用XmlOverrideAttributes来说明
<Foo>
<Bars>
<SomethingElse>...</SomethingElse>
</Bars>
</Foo>
但我似乎无法让它重命名集合中的子元素...我可以重命名集合本身...我可以重命名根...不确定我做错了什么。< / p>
这是我现在的代码:
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();
但这根本不会改变元素的名称......我做错了什么?
感谢
答案 0 :(得分:8)
为此,您需要[XmlArray]
和[XmlArrayItem]
(理想情况下两者都要明确):
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
public class Foo {
public List<Bar> 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<Bar> {
new Bar { Widget = "widget"}
}};
serializer.Serialize(writer, foo);
string xml = writer.ToString();
}
}
}
答案 1 :(得分:1)
德里克,
这对我有用 - 不确定它是否适合你:
public class Foo
{
[XmlArrayItem(ElementName = "SomethingElse")]
public List<Bar> Bars { get; set; }
}