XML到IEnumerable <t> </t>

时间:2009-09-22 14:52:43

标签: c# asp.net xml linq

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

例如,我可能有一个像

这样的XML文件
<fruits>
    <fruit>
        <id>1</id>
        <name>apple</name>
    </fruit>
    <fruit>
        <id>2</id>
        <name>orange</name>
    </fruit>
</fruits>

我希望看到一个水果对象列表

它具有类似

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

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

提前致谢

3 个答案:

答案 0 :(得分:9)

考虑以下类型:

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; }
}

我认为你可以这样做:

    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);

答案 1 :(得分:3)

这是一种使用序列化的方法,如果这是你的事情:

using System;
using System.IO;
using System.Xml.Serialization;

public static class Test
{
    public static void Main(string[] args)
    {
        var fs = new FileStream("fruits.xml", FileMode.Open);
        var x = new XmlSerializer(typeof(Fruits));
        var fruits = (Fruits) x.Deserialize(fs);
        Console.WriteLine("{0} count: {1}", fruits.GetType().Name, fruits.fruits.Length);
        foreach(var fruit in fruits.fruits)
            Console.WriteLine("id: {0}, name: {1}", fruit.id, fruit.name);
    }
}

[XmlRoot("fruits")]
public class Fruits
{
    [XmlElement(ElementName="fruit")]
    public Fruit[] fruits;
}

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

答案 2 :(得分:0)

我不确定我是否完全了解您的情况,但一种方法是定义数据传输类并使其可以在XML中进行序列化。然后,您可以将XML反序列化为对象数组。

修改

我不会删除这个,但我认为Andrew Hare发布的内容更接近你想要的内容,而且我已经投票支持他了。

相关问题