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

如何让C# XmlSerializer序列化时移除Children节点,将MyChild直接嵌入MyHeader?

最简解决方案:给集合属性添加[XmlElement]特性

嘿,这个需求其实超容易实现,核心就是用XmlSerializer的特性来改变集合的序列化行为!

具体修改步骤

只需要在MyHeader类的Children属性上添加[XmlElement]特性就行,代码修改如下:

// 别忘了引用System.Xml.Serialization命名空间
using System.Xml.Serialization;

public class MyHeader {
    public string Identification { get; set; }
    public DateTime Date { get; set; }
    public string Description { get; set; }
    
    // 添加XmlElement特性,指定子元素名为"MyChild"(也可以省略,默认会用类型名)
    [XmlElement("MyChild")]
    public List<MyChild> Children { get; set; }
}

public class MyChild {
    public string Identification { get; set; }
    public string Description { get; set; }
}

// GetXML方法完全不用改,保持原来的逻辑就行
public string GetXML() {
    var h = new MyHeader {
        Date = DateTime.Now,
        Description = "Something",
        Identification = "AAAAA11111",
        Children = new List<MyChild> {
            new MyChild { Identification = "B1", Description = "B1"},
            new MyChild { Identification = "B2", Description = "B2"},
            new MyChild { Identification = "B3", Description = "B3"}
        }
    };
    var xml = "";
    var serializer = new XmlSerializer(h.GetType());
    using (var sww = new StringWriter()) {
        using (XmlWriter writer = XmlWriter.Create(sww)) {
            serializer.Serialize(writer, h);
            xml = sww.ToString();
        }
    }
    return xml;
}

原理说明

默认情况下,XmlSerializer处理集合属性时,会自动生成一个包裹节点(比如你的原代码里的<Children>),然后把集合里的每个元素都放在这个包裹节点里面。而[XmlElement]特性会告诉序列化器:“别生成外层的包裹节点了,直接把每个子元素当成父节点的直接子节点输出”,这样就正好符合你想要的XML结构。

最终效果

修改后运行GetXML(),得到的XML就是你期望的样子:

<?xml version="1.0" encoding="utf-16"?>
<MyHeader xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Identification>AAAAA11111</Identification>
  <Date>2020-09-09T11:55:04.2457349+02:00</Date>
  <Description>Something</Description>
  <MyChild>
    <Identification>B1</Identification>
    <Description>B1</Description>
  </MyChild>
  <MyChild>
    <Identification>B2</Identification>
    <Description>B2</Description>
  </MyChild>
  <MyChild>
    <Identification>B3</Identification>
    <Description>B3</Description>
  </MyChild>
</MyHeader>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 07:47:46