+ Reply to Thread
Results 1 to 3 of 3

Thread: Deserialize Unknown Type

  1. #1

    Deserialize Unknown Type

    I have the following XML Code:
    Code:
    <property name="someName" value="someValue" />
    I thouth of Alternative code , this could be:
    Code:
    <property name="someName" value="5" />
    Or:
    Code:
    <property name="someName" value="true" />
    And so on .... :
    Code:
    [Serializable]
    [XmlType("property")]
    public class Property
    {
        [XmlAttribute("name")]
        public string Name { get; set; }
        [XmlAttribute("value")]
        public object Value { get; set; }
    
        public Property()
        {
    
        }
    }
    The above code does not work. I can use string, or anything specific as long as it is always that specific type. I was hoping object would allow any known type work.

  2. #2
    Junior Member
    Join Date
    Jan 2012
    Posts
    30
    Well, how would the xml serializer know whether you want to store the string "5" or the actual number 5? You either need to implement the IXmlSerializable interface or you might be able to do apply a workaround , anyway here is a sample of materialization code , hope it helps .
    Code:
    [Serializable]
    [XmlType("property")]
    public class Property
    {
        [XmlAttribute("name")]
        public string Name { get; set; }
        [XmlAttribute("value")]
        public string StringValue { get; set; }
    
        private object _Value;
        [XmlIgnore]
        public object Value
        {
            get
            {
                if (_Value == null)
                {
                     _Value = CreateFromStringValue();
                }
                return _Value;
            }
        }
    
        public Property()
        {
        }
    
        private object CreateFromStringValue()
        {
           // parse StringValue in here as you see fit (e.g. first try bool, then int, float, etc.)
        }
    }

  3. #3
    Thank you very much .

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts