Histerical
Histerical

Reputation: 304

Deserialize xml attribute to List<String>

I am trying to deserialize an attribute with a list of pages to a List<String> object. If I use a space delimiter, I am able to deserialize it just fine, but I want it to look cleaner with a comma or a vertical bar.

Is it possible to deserialize

<Node Pages="1,2">

into a List<String> or List<int>?

My class is simple as well.

public List<int> Pages;

Upvotes: 0

Views: 2229

Answers (1)

mstaessen
mstaessen

Reputation: 1317

XmlSerializer does not support this out of the box for attributes. If you are in control of the structure of the XML, consider using child elements because using character separated attribute strings kind of beats the purpose of XML altogether.

You could work around it though using a computed property. But bear in mind that this will be slower because every time you access this property, you will parse the comma-separated string.

[XmlAttribute(AttributeName = "Pages")]
public string PagesString { get; set; }

public IList<int> Pages {
    get {
        return PagesString.Split(',').Select(x => Convert.ToInt32(x.Trim())).ToList();
    }
    set {
       PagesString = String.Join(",", value);
    }
}

Also, this silly implementation does not take into account that there might be wrong input in your string. You should guard against that too.

Another thing to notice is that every time you access the Pages property, a new collection is returned. If you invoke Add() on the returned value, this change will not be reflected in your XML.

Upvotes: 2

Related Questions