简体   繁体   中英

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM