如何在 C# 中动态地将 class 数组转换为 XML 文件?

How to convert class Array to XML file in C# dynamically?

我试图建立一个 Xml 文件,其数据为 class 数组格式。基本 class 格式是

订单模板Class

public partial class OrderTemplate {
        public int Id { get; set; }
        public int? OrderNumberCounterId { get; set; }
        public int? SerialCounterId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int? Critical { get; set; }

        public Counter OrderNumberCounter { get; set; }
        public ICollection<OperationTemplate> OperationTemplate { get; set; }
        public ICollection<OrderTemplateAssemblyUnit> OrderTemplateAssemblyUnit { get; set; }


}

下面给出各自的转换函数

public async Task<IActionResult> UploadXML([FromBody] OrderTemplate[] XMLData)
        {
            try
            {


                string fileName = "OrderTemplateXMLData.xml";
                var folderName = Path.Combine("Uploads", "XMLUploads");
                var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);

                var fullPath = Path.Combine(pathToSave, fileName);
                var dbPath = Path.Combine(folderName, fileName);                               

                 XDocument doc = new XDocument();
// Thinks the problem is here 
                 doc.Add(new XElement("OrderTemplate",XMLData.Select(x => new XElement("item", x)))); 

                if (Convert.ToString(XMLData).Length > 0)
                {

                    return Ok(new { dbPath });
                }
                else
                {
                    return BadRequest();
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, "Internal server error");
            }
        }
    }

当前结果

目前我用这样的数据生成了 Xml 文件。

<?xml version="1.0" encoding="UTF-8"?>

<OrderTemplate>
  <Data>KappDmsApi.Models.OrderTemplate</Data>
  <Data>KappDmsApi.Models.OrderTemplate</Data>
</OrderTemplate>

实际结果

但我需要像这样更改 Header 的数据。

<OrderTemplate>
    <Order>
        <id>3</id>
        <orderNumberCounterId>1</orderNumberCounterId>
        <serialCounterId>3</serialCounterId>
        <name>Toyota FS Back</name>
        <description>Toyota FS Back</description>
        <critical>0</critical>
        <orderNumberCounter>null</orderNumberCounter>
    </Order>
    <Order>
        <id>6</id>
        <orderNumberCounterId>1</orderNumberCounterId>
        <serialCounterId>3</serialCounterId>
        <name>Toyota FS Cushion</name>
        <description>Toyota FS Cushion</description>
        <critical>0</critical>
        <orderNumberCounter>null</orderNumberCounter>
    </Order>                   
</OrderTemplate>

如何处理这种情况?上面的代码有什么要改的吗?

不要手动构建 XML 文件,而是使用 XML 序列化程序实例。

为了正确生成结构,请使用包装器-class 具有如下修饰属性:

class XmlOrderTemplate {
  [XmlArray("OrderTemplate")]
  [XmlArrayItem("Order")]
  public List<OrderTemplate> Orders {get;set;}
}

using(var sw = new StreamWriter(fullPath)){
  var serializer = new XmlSerializer(typeof(XmlOrderTemplate));
   serializer.Serialize(sw, new XmlOrderTemplate {Orders = Data});
}