0

这是我的两个类:类 Characteristic 和 Definition :

[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" />        

4

1 回答 1

1

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

要将其序列化为字符串:

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);
}
于 2019-11-13T09:44:45.637 回答