通过 XElement_Not 将属性作为 XMLAttribute

Put attributes via XElement_Not as XMLAttribute

这是我的两个 classes:class 特征和定义:

[DataContract]
    public class Characteristic
    {
        [DataMember]
        public Definition Definition { get; set; }
    }

  [Serializable]
    public class Definition
    {
        [XmlAttribute]
        public int id;
        [XmlAttribute]
        public stringName;
    }

这是我的实现:

     Characteristic lstChars = new Characteristic()
                        {
                            Definition = new Definition()
                            {
                                id = Dimension.ID,
                                name = Dimension.Name
                            }
                        };

我得到这个结果:

<Characteristic>
  <Definition>
         <id>6</id>
          <name>ACTIVITY</name>
  </Definition>

我的目标是得到这个结果:

<Characteristic>

  <Definition id="6" Name= "ACTIVITY" />        

为了序列化,可以使用以下方式:

序列化为字符串:

string result;

using (var writer = new StringWriter())
{
    new XmlSerializer(typeof(Characteristic)).Serialize(writer, lstChars);
    result = writer.ToString();
}

将其序列化并存储在文件中:

using (var writer = new StreamWriter(xmlFilePath))
{
    new XmlSerializer(typeof(Characteristic)).Serialize(writer, lstChars);
}