XML到IEnumerable< T> [英] XML to IEnumerable<T>

查看:89
本文介绍了XML到IEnumerable< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法获取给定的XML文件并将其转换(最好使用C#泛型)到T的具体可枚举列表中,其中T是我的具体类

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

例如,我可能有一个XML文件,例如

So for example I may have an XML file like

<fruits>
    <fruit>
        <id>1</id>
        <name>apple</name>
    </fruit>
    <fruit>
        <id>2</id>
        <name>orange</name>
    </fruit>
</fruits>

我想查看一个Fruit Objects的列表

and I would like to see a list of a Fruit Objects

具有类似

public class Fruit : IFruit
{
    public string name;
    public int id;
}

如果我要使用泛型,我想我需要某种映射,因为我希望它可以理想地用于IFruit接口(不确定是否可行)

I assume I'd need some kind of Mapping if I was to use generics, as I would like this to work for ideally the IFruit interface (not sure if thats possible)

预先感谢

推荐答案

给出以下类型:

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<T> GetSomeFruit<T>(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)
            });
    }

您会这样称呼:

IEnumerable<Fruit> fruit = GetSomeFruit<Fruit>(yourXml);

这篇关于XML到IEnumerable&lt; T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆