c#从xml返回所有特定元素

时间:2011-04-01 11:44:31

标签: c# xml linq ienumerable

问候。我有一个小麻烦,我希望得到一些帮助。我有一个非常大的xml文件,大约有1000个客户,提供不同的客户信息。我想做一些方法来检索这些信息。我一直在寻找,但似乎无法找到我想要的东西。目前正在尝试:

public custInformation getcustInfo(string file) {      
    //Load the xml file
    var xe = XDocument.Load(_server.MapPath(file)).Root;

    //Get information
    return (from p in xe.Descendants("cust-account").Descendants("cust-info")
            select new custInformation
            {
                firstName = (string)p.Element("cust-fname"),
                lastName = (string)p.Element("cust-lname"),
                address = (string)p.Element("cust-address1"),
            }).(All elements)??   
}

(所有元素)是id想要检索所有信息的地方。使用FirstOrDefault只会检索第一个元素,而LastOrDefault只会检索第一个元素。如果有人可以帮助我,我会非常感激。

1 个答案:

答案 0 :(得分:0)

您需要一份客户列表。将返回值更改为IEnumerable  并使用ToList()/ ToArray()将查询转换为IEnumerable:

public IEnumerable<custInformation> getcustInfo(string file) {      
    //Load the xml file
    var xe = XDocument.Load(_server.MapPath(file)).Root;

    //Get information
    return (from p in xe.Descendants("cust-account").Descendants("cust-info")
            select new custInformation
            {
                firstName = (string)p.Element("cust-fname"),
                lastName = (string)p.Element("cust-lname"),
                address = (string)p.Element("cust-address1"),
            }).ToList();
}
相关问题