这应该很简单,但我在这里遗漏了一些东西。序列化我的课程时,我需要以下格式的输出 xml。
<items>
<item id="1" name="John">
<item id="2" name="Peter">
<item id="3" name="Shane">
<items>
这是课程:
public class Item
{
[XmlAttribute]
public string Id;
[XmlAttribute]
public string Name;
}
这是我的测试代码:
var items = new List<Item>();
for (int i = 0; i < 4; i++)
{
var item = new Item();
item.Id = i.ToString();
item.Name = "Jeff" + " - " + i.ToString();
items.Add(item);
}
Ser(items);
static void Ser(object o)
{
XmlSerializer x = new XmlSerializer(o.GetType());
var xns = new XmlSerializerNamespaces();
xns.Add(string.Empty, string.Empty);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
XmlWriter writer = XmlWriter.Create(Console.Out, settings);
x.Serialize(writer, o, xns);
Console.WriteLine();
}
我得到的输出是:
<ArrayOfItem>
<Item Id="0" Name="Jeff - 0" />
<Item Id="1" Name="Jeff - 1" />
<Item Id="2" Name="Jeff - 2" />
<Item Id="3" Name="Jeff - 3" />
</ArrayOfItem>
我想用“Items”替换“ArrayOfItem”。另外,为什么我看到附加了“ArrayOf”?提前致谢。