如何在LINQ中查询此XML?

我发现使用XML中的属性和嵌套元素很难。 如果我只想提取具有Type="Mobile"属性的Phone元素并在一行中打印地址,我该如何在LINQ中执行此操作?

我想生成一个像这样的输出:

 332-899-5678 | 123 Main, St Mercer Island, WA 68042 

请帮忙,下面是我的示例xml文件

   Patrick Hines 206-555-0144 425-555-0145 332-899-5678 
123 Main St Mercer Island WA 68042

 string xml = @"  Patrick Hines 206-555-0144 425-555-0145 332-899-5678 
123 Main St Mercer Island WA 68042
Dorothy Lee 910-555-1212 336-555-0123 336-555-0005
16 Friar Duck Ln Greensboro NC 27410
"; XDocument document = XDocument.Parse(xml); var query = from contact in document.Descendants("Contact") let address = contact.Element("Address") select new { Name = contact.Element("Name").Value, MobilePhone = contact.Elements("Phone").Where(ele => ele.Attribute("Type").Value == "Mobile").First().Value, Street1 = address.Element("Street1").Value, City = address.Element("City").Value, State = address.Element("State").Value, Postal = address.Element("Postal").Value }; foreach (var item in query) { Console.WriteLine("{0} | {1}, {2}, {3} {4}", item.MobilePhone, item.Street1, item.City, item.State, item.Postal); }

也许是这样的:

 var rows = from contact in root.Elements("Contact") let phone = (string)contact.Elements("Phone").FirstOrDefault( (string)p => p.Attribute("Type") == "Mobile") let addr = contact.Element("Address") select phone + " | " + (string)addr.Element("Street1") + " | " + (string)addr.Element("City") + " | " + ...