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.

1

2 Answers 2

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);}
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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; }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.