Linq-to-XMLquerytoselectspecificchildelementsbasedonothercriteria我目前的LINQ查询和示例XML如下所示。我想要做的是从email-addresses元素中选择主要电子邮件地址到User.Email属性。这里最简单的方法是什么?当前Linq查询(User.Email当前为空):varusers=fromresponseinxdoc.Descendants("response")whereresponse.Element("id")!=nullselectnewUser{Id=(string)response.Element("id"),Name=(string)response.Element("full-name"),Email=(string)response.Element("email-addresses"),JobTitle=(string)response.Element("job-title"),NetworkId=(string)response.Element("network-id"),Type=(string)response.Element("type")};示例XML:primaryalice@domain.com客户经理用户东部时间(美国和加拿大)域Alice79629243http://sofzh.miximages.com/c%23/no_photo_small.gifalicehttps://www.yammer.com/domain.com/users/aliceactivehttps://www.yammer.com/api/v1/users/1089943domain.com1089943primarybill@domain.comOfficeManager用户东部时间(美国和加拿大)DomainBill79629311http://sofzh.miximages.com/c%23/no_photo_small.gif账单https://www.yammer.com/domain.com/users/billactivehttps://www.yammer.com/api/v1/users/1089920domain.com1089920使用Lambda表达式:varusers=xdoc.Root.Elements("response").Where(x=>!string.IsNullOrEmpty(x.Element("id").Value)).Select(x=>newUser{Id=x.Element("id").Value,Name=x.Element("全名").Value,Email=x.Descendants("email-address").Where(y=>y.Element("type").Value=="primary").First().Element("address").Value,JobTitle=x.Element("job-title").Value,NetworkId=x.Element("network-id").Value,Type=x.Element("type").Value,});查询表达式没有太大区域别:varusers=fromresponseinxdoc.Descendants("response")whereresponse.Element("id")!=nullselectnewUser{Id=response.Element("id").Value,Name=response.Element("full-name").Value,Email=response.Descendants("email-address").Where(x=>x.Element("type").Value=="primary").First().Element("address").Value,JobTitle=response.Element("job-title").Value,NetworkId=response.Element("network-id").Value,Type=response.Element("type").Value};像这样:response.Descendants("email-address").Single(a=>a.Element("type").Value=="primary").Element("address").Value请注意,如果没有一个匹配的元素,这将抛出异常如果你不这样做想要这个,请致电FirstOrDefault。您可能需要将.Descendants("email-address")替换为.Descendants("email-address").Element("contact").Element("email-addresses").Element("email-addresses").Element("email-addresses")地址").以上就是C#学习教程:Linq-to-XML查询根据其他条件选择特定子元素的全部内容分享。如果对大家有用,需要进一步了解C#学习教程,还望大家多多关注。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
