序列化 Class 具有 属性 类型的对象

Serializing Class having property of type object

Type对象的属性值可以是任何类型的单个值,如int、string、decimal等。也可以是值的集合,如List、List等。

public class Criteria
{
    [XmlElement("IDS")]
    public object Value
    {
        get; set;
    }
}

当前输出:

<CriteriaGroup>
  <Criteria p2:type="Criteria" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance">
    <IDS p2:type="ArrayOfInt">
      <int>2610</int>
      <int>2452</int>
    </IDS>
  </Criteria>
  <Criteria p2:type="Criteria" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance">
    <IDS p2:type="ArrayOfString">
      <string>CUMULU1MO</string>
      <string>ALLIEDWX2</string>      
    </IDS>
  </Criteria>
</CriteriaGroup>

预期输出:

我怎样才能达到下面的结果?尝试用 XmlArray、XmlArrayItem 装饰 public 对象值,但没有成功。

<CriteriaGroup>
  <Criteria>
    <IDS>
      <ID>2610</ID>
      <ID>2452</ID>
    </IDS>
  </Criteria>
  <Criteria>
    <IDS>
      <ID>CUMULU1MO</ID>
      <ID>ALLIEDWX2</ID>      
    </IDS>
  </Criteria>
</CriteriaGroup>

使用下面的方法序列化。

public static string Serialize<T>(T data)
{
    string xmlData = string.Empty;
    XmlSerializer ser = new XmlSerializer(typeof(T));
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add("", "");
    
    var settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.OmitXmlDeclaration = true;
    
    using (StringWriter sw = new StringWriter())
    {
        using (XmlWriter xw = XmlWriter.Create(sw, settings))
        {
            ser.Serialize(xw, data, ns);
            xmlData = sw.ToString();
        }
    
    }
    return xmlData;
}

尝试以下操作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            CriteriaGroup CriteriaGroup = new CriteriaGroup()
            {
                Criteria = new List<Criteria>() {
                    new Criteria() { Value = new string[] { "2610","2452"}
                    },
                    new Criteria() { Value = new string[] {"CUMULU1MO", "ALLIEDWX2"}
                    }
                }
            };
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            XmlWriter writer = XmlWriter.Create(FILENAME, settings);
            XmlSerializer serializer = new XmlSerializer(typeof(CriteriaGroup));
            serializer.Serialize(writer, CriteriaGroup);
        }
    }
    public class CriteriaGroup
    {
        [XmlElement()]
        public List<Criteria> Criteria { get; set; }
    }
    public class Criteria
    {
        [XmlArray("IDS")]
        [XmlArrayItem("ID")]
        public string[] Value
        {
            get;
            set;
        }
    }
}