我從List<int>
派生並希望使用自定義名稱進行XML序列化。例如:列表的命名XML序列化
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
namespace xmlerror
{
[Serializable, XmlRoot("Foo")]
public class Foo : List<int>
{
}
class MainClass
{
public static void Main(string[] args)
{
var foo = new Foo();
foo.Add(123);
using (var writer = new StringWriter())
{
var serilizer = new XmlSerializer(typeof(Foo));
serilizer.Serialize(writer, foo);
Console.WriteLine(writer.ToString());
}
}
}
}
輸出:
<?xml version="1.0" encoding="utf-16"?>
<Foo xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<int>123</int>
</Foo>
但我想命名元素<Bar>
而不是<int>
。我嘗試了XML屬性XmlAnyElement
和XmlArrayItem
,但沒有結束。我如何更改元素標籤的名稱?我必須手動使用XmlTextWriter
嗎?
這也適用,但我決定使用其他答案。 – aggsol