You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# XML序列化:移除列表子类的数组名称标签

解决XmlSerializer生成冗余数组标签的问题

要去掉<elements>、<Children>这类冗余容器标签,直接将集合内的元素作为父节点的子元素,你需要把原来的XmlArray和XmlArrayItem特性替换为多个XmlElement特性,每个特性指定对应子类的元素名称和类型。

修改后的完整代码

[Serializable]
public class FunctionList
{
    [XmlAttribute("name")]
    public string Name { get; set; }

    // 用XmlElement替代XmlArray,直接生成子元素
    [XmlElement("Space", typeof(Space))]
    [XmlElement("Device", typeof(Device))]
    public List<DesignElement> elements { get; set; }
}

[Serializable]
public abstract class DesignElement
{
    [XmlAttribute("title")]
    public string Title { get; set; }
}

[Serializable]
public class Space : DesignElement
{
    // 同样替换为XmlElement,去掉Children容器标签
    [XmlElement("Space", typeof(Space))]
    [XmlElement("Device", typeof(Device))]
    public List<DesignElement> children { get; set; }
}

[Serializable]
public class Device : DesignElement
{

}

序列化后的XML示例

假设你构造如下对象:

var functionList = new FunctionList
{
    Name = "TestList",
    elements = new List<DesignElement>
    {
        new Space { Title = "RootSpace", children = new List<DesignElement>
            {
                new Device { Title = "InnerDevice" },
                new Space { Title = "SubSpace" }
            }
        },
        new Device { Title = "OuterDevice" }
    }
};

生成的XML会是这样(没有冗余的<Element>或<Children>标签):

<FunctionList name="TestList">
  <Space title="RootSpace">
    <Device title="InnerDevice" />
    <Space title="SubSpace" />
  </Space>
  <Device title="OuterDevice" />
</FunctionList>

原理说明

  • XmlArray特性会强制生成一个包裹集合的容器标签(比如原来的<Element>),而XmlElement特性会直接将集合中的每个元素序列化为父节点的直接子元素。
  • 多个XmlElement特性可以为不同的子类指定对应的XML元素名称,XmlSerializer会根据对象的实际类型自动匹配对应的元素名。

内容的提问来源于stack exchange,提问作者Lennart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 01:26:07