如何在LINQ中查询此XML? [英] How to query this XML in LINQ?

查看:62
本文介绍了如何在LINQ中查询此XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I find it hard using attributes and nested elements in XML. How should I do this in LINQ if I want to extract only the Phone element with the attribute Type="Mobile" and print the address in one line?

我想产生这样的输出:

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

请帮助,以下是我的示例XML文件

Please help, below is my sample xml file

<Contacts>
  <Contact>
    <Name>Patrick Hines</Name>
    <Phone Type="Home">206-555-0144</Phone>
    <Phone Type="Work">425-555-0145</Phone>
    <Phone Type="Mobile">332-899-5678</Phone>
    <Address>
      <Street1>123 Main St</Street1>
      <City>Mercer Island</City>
      <State>WA</State>
      <Postal>68042</Postal>
    </Address>
  </Contact>
</Contacts> 

推荐答案

string xml = @"<Contacts> 
    <Contact> 
    <Name>Patrick Hines</Name> 
    <Phone Type=""Home"">206-555-0144</Phone> 
    <Phone Type=""Work"">425-555-0145</Phone> 
    <Phone Type=""Mobile"">332-899-5678</Phone> 
    <Address> 
        <Street1>123 Main St</Street1> 
        <City>Mercer Island</City> 
        <State>WA</State> 
        <Postal>68042</Postal> 
    </Address> 
    </Contact> 
    <Contact> 
    <Name>Dorothy Lee</Name> 
    <Phone Type=""Home"">910-555-1212</Phone> 
    <Phone Type=""Work"">336-555-0123</Phone> 
    <Phone Type=""Mobile"">336-555-0005</Phone> 
    <Address> 
        <Street1>16 Friar Duck Ln</Street1> 
        <City>Greensboro</City> 
        <State>NC</State> 
        <Postal>27410</Postal> 
    </Address> 
    </Contact>
</Contacts>";

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

这篇关于如何在LINQ中查询此XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆