1

I have a XML file:

<Hand cards="C5,SQ,DQ,H8,C9,H7,S9,D5,DA,CJ,S6,HK,D4">
</Hand>

I define a class

[Serializable()]
[XmlRoot("Hand")]
public class Hand
{
    [XmlAttribute("cards")]
    public List<string> Cards{get;set;}
}

How to deserialize a XML to object in this case? Hand object result must have Cards = {C5,SQ,DQ,H8,C9,H7,S9,D5,DA,CJ,S6,HK,D4}.

Amar Palsapure
  • 9,590
  • 1
  • 27
  • 46
Leo Vo
  • 9,980
  • 9
  • 56
  • 78
  • Heres an easy starting point for the basics on MSDN http://msdn.microsoft.com/en-us/library/182eeyhh(v=vs.100).aspx – Lloyd Feb 10 '12 at 08:22
  • 1
    You will have to do a custom serialization. See http://stackoverflow.com/q/1075860/24047. – bang Feb 10 '12 at 08:23

2 Answers2

5

You cannot.

What you can do is to create a property which will do this conversion in its getter/setter

[XmlIgnore]
public List<string> CardList { get; private set; }

[XmlAttribute("cards")]
public string Cards {
   get { return String.Join(",", CardList); }
   set { CardList = value.Split(",").ToList(); }
}
Alexey Raga
  • 7,457
  • 1
  • 31
  • 40
2

You can do this with the help of IXmlSerializable. Read more about it on MSDN.

This way

[Serializable()]
[XmlRoot("Hand")]
public class Hand : IXmlSerializable {
    [XmlAttribute("cards")]
    public List<string> Cards { get; set; }

    public System.Xml.Schema.XmlSchema GetSchema() { return null; }

    public void ReadXml(XmlReader reader) {
        this.Cards = new List<string>(reader.GetAttribute("cards").Split(','));
    }

    public void WriteXml(XmlWriter writer) {
        writer.WriteAttributeString("cards", 
             string.Join(",", 
                this.Cards != null ? this.Cards : new List<string>()));
    }
}

Hope this helps you.

Amar Palsapure
  • 9,590
  • 1
  • 27
  • 46