道歉但无法更具体地说出标题,但我只能举一个例子来解释。
我正在尝试构建一个序列化为以下XML的类
<Customize>
<Content></Content>
<Content></Content>
<!-- i.e. a list of Content -->
<Command></Command>
<Command></Command>
<Command></Command>
<!-- i.e. a list of Command -->
</Customize>
我的C#是:
[XmlRoot]
public Customize Customize { get; set; }
和
public class Customize
{
public List<Content> Content { get; set; }
public List<Command> Command { get; set; }
}
但是,这会产生(应该如此),以下内容:
<Customize>
<Content>
<Content></Content>
<Content></Content>
</Content>
<Command>
<Command></Command>
<Command></Command>
<Command></Command>
</Command>
</Customize>
是否有一些xml序列化属性可以帮助我实现所需的xml,或者我是否必须找到另一种编写类的方法?
答案 0 :(得分:2)
使用XmlElementAttribute
标记您的收藏品属性。</ p>
public class Customize
{
[XmlElement("Content")]
public List<Content> Content { get; set; }
[XmlElement("Command")]
public List<Command> Command { get; set; }
}
快速测试代码:
var item = new Customize() { Content = new List<Content> { new Content(), new Content() }, Command = new List<Command> { new Command(), new Command(), new Command() } };
string result;
using (var writer = new StringWriter())
{
var serializer = new XmlSerializer(typeof(Customize));
serializer.Serialize(writer, item);
result = writer.ToString();
}
打印:
<?xml version="1.0" encoding="utf-16"?>
<Customize xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Content />
<Content />
<Command />
<Command />
<Command />
</Customize>
答案 1 :(得分:1)
public class Customize
{
[XmlElement("Content")]
public List<Content> Content { get; set; }
[XmlElement("Command")]
public List<Command> Command { get; set; }
}