Search code examples
c#xmlxattribute

Put attributes via XElement_Not as XMLAttribute


Here is my two classes: the class Characteristic and Definition :

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

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

and this is my implementation :

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

I get this result:

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

And my objectif is to get this result:

<Characteristic>

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


Solution

  • In order to serialize it, you can use the following ways:

    To serialize it into a string:

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

    To serialize and store it on a file:

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