【问题标题】:c# return all specific elements from an xmlc# 从 xml 返回所有特定元素
【发布时间】:2011-04-01 11:44:31
【问题描述】:

您好。我遇到了一个小麻烦,我想得到一些帮助。我有一个非常大的 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)??   
}

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

【问题讨论】:

    标签: c# xml linq ienumerable


    【解决方案1】:

    您需要一份客户列表。将返回值更改为 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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      • 2013-04-22
      • 1970-01-01
      • 2014-11-25
      • 1970-01-01
      • 2020-07-12
      • 2021-03-30
      相关资源
      最近更新 更多