XML to IEnumerable

后端 未结 3 531
旧时难觅i
旧时难觅i 2021-02-09 15:42

Is there a way to Take a given XML file and convert (preferably using C# Generics) it into a Concrete Ienumerable list of T where T is my concrete class

So for example

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-09 15:59

    Given the following types:

    public interface IFruit
    {
        String name { get; set; }
        Int32 id { get; set; }
    }
    
    public class Fruit : IFruit
    {
        public String name { get; set; }
        public Int32 id { get; set; }
    }
    

    I think that you could do something like this:

        static IEnumerable GetSomeFruit(String xml)
            where T : IFruit, new()
        {
            return XElement.Parse(xml)
                .Elements("fruit")
                .Select(f => new T {
                    name = f.Element("name").Value,
                    id = Int32.Parse(f.Element("id").Value)
                });
        }
    

    Which you would call like this:

    IEnumerable fruit = GetSomeFruit(yourXml);
    

提交回复
热议问题