简体   繁体   English

如何在LINQ中查询此XML?

[英]How to query this XML in LINQ?

I find it hard using attributes and nested elements in XML. 我发现很难使用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? 如果我只想提取属性为Type="Mobile"Phone元素并在一行中打印地址,该如何在LINQ中执行此操作?

I want to produce an output just like this: 我想产生这样的输出:

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

Please help, below is my sample xml file 请帮忙,以下是我的示例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>
</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);
}

Perhaps something like: 也许像这样:

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") + " | " +
         ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM