当我从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>
我很想知道我是否可以修改&#34; GetXElement&#34;尊重&#34; Widget&#34;的XmlRoot属性,但我对其他想法持开放态度,只要我仍然可以从列表继承。我不喜欢这里给出的解决方案:Serialize a generic collection specifying element names for items in the collection
答案 0 :(得分:1)
[XmlType(TypeName = "Foo")]
[Serializable]
public class Widget
{
public int ID { get; set; }
}