0

I've created a object that is serializable and I want to serialize it to XML and then later deserialize back. What I want though is to save one property of this object as XML attribute. Here is what I mean:

[Serializable]
public class ProgramInfo
{
    public string Name { get; set; }
    public Version Version { get; set; }
}

public class Version
{
    public int Major { get; set; }
    public int Minor { get; set; }
    public int Build { get; set; }
}

I want to save ProgramInfo to XML file that looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<ProgramInfo Name="MyApp" Version="1.00.0000">

</ProgramInfo>

Notice the Version property and its corresponding attribute in XML. I already have parser that turns string "1.00.0000" to valid Version object and vice-versa, but I don't know how to put it to use with this XML serialization scenario.

ProgramFOX
  • 6,131
  • 11
  • 45
  • 51
matori82
  • 3,669
  • 9
  • 42
  • 64
  • Possible duplicate of http://stackoverflow.com/questions/11330643/serialize-property-as-xml-attribute-in-element – atomaras Nov 15 '13 at 17:26

2 Answers2

2

What you need is a property for the string representation that gets serialized:

[Serializable]
public class ProgramInfo
{
    [XmlAttribute]
    public string Name { get; set; }

    [XmlIgnore]
    public Version Version { get; set; }

    [XmlAttribute("Version")
    public string VersionString 
    { 
      get { return this.Version.ToString(); } 
      set{ this.Version = Parse(value);}
    }
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240
1

What you could do is have a VersionValue and a VersionType Property

[Serializable]
public class ProgramInfo
{
  private string _versionValue;
  public string Name { get; set; }
  public string VersionValue 
  { 
    get
    {
      return _versionValue;
    }
    set{
       _versionValue = value;
       //Private method to parse
       VersonType = parseAndReturnVersionType(value);

       } 
  }
  public Version VersionType { get; set; }
}
Bearcat9425
  • 1,580
  • 1
  • 11
  • 12