0

抱歉无法更具体地表达标题,但我只能通过举例来解释。

我正在尝试构建一个序列化为以下 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,还是我必须找到另一种编写类的方法?

4

2 回答 2

2

用于XmlElementAttribute标记您的集合属性。

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>
于 2013-11-05T01:41:26.667 回答
1
public class Customize
{
    [XmlElement("Content")]
    public List<Content> Content { get; set; }

    [XmlElement("Command")]
    public List<Command> Command { get; set; }
}
于 2013-11-05T01:40:33.560 回答