多个相同元素的LINQ-to-XML查询

时间:2014-09-09 19:41:26

标签: c# linq linq-to-xml

我是LINQ和XML的新手,我正在尝试使用现有的大型500k行XML文件,该文件与下面的XML具有相同的结构。我已经想出了如何测试多个null XElements,但我完全坚持如何搜索多个相同的XElements。

如何让LINQ返回仅适用于谷歌的联系人?

先谢谢大家。

void Main()
{
XDocument AddressBook = CreateAddressBookXML();

var query =
        from contact in AddressBook.Descendants("Contact")
        let companyelement = contact.Element("Company") 
        where companyelement != null
        let companyname    = companyelement.Descendants("CompanyName")
        where companyname != null && companyname == "Google"
        select contact;


Console.Write(query);

}


public XDocument CreateAddressBookXML() {
    XDocument result =
      new XDocument(
        new XComment("My phone book"),
        new XElement("phoneBook",
          new XComment("My friends"),
          new XElement("Contact",
            new XAttribute("name", "Ralph"),
            new XElement("homephone", "555-234-4567"),
            new XElement("cellphone", "555-345-75656"),
            new XElement("Company",
                new XElement("CompanyName","Ralphs Web Design"),
                new XElement("CompanyName","Google")
            )
        ),
          new XElement("Contact",
            new XAttribute("name", "Dave"),
            new XElement("homephone", "555-756-9454"),
            new XElement("cellphone", "555-762-1546"),
            new XElement("Company",
                new XElement("CompanyName","Google")
            )
        ),
          new XComment("My family"),
          new XElement("Contact",
            new XAttribute("name", "Julia"),
            new XElement("homephone", "555-578-1053"),
            new XElement("cellphone", "")
        ),
          new XComment("My team"),
          new XElement("Contact",
            new XAttribute("name", "Robert"),
            new XElement("homephone", "555-565-1653"),
            new XElement("cellphone", "555-456-2567"),
            new XElement("Company",
                new XElement("CompanyName","Yahoo")
                )
        )
    )
  );

    return result;
}

2 个答案:

答案 0 :(得分:0)

var query = from contacts in CreateAddressBookXML().Root.Descendants("Contact")
            where contacts.Element("Company") != null &&
                  contacts.Element("Company").Elements("CompanyName").
            FirstOrDefault(c => c.Value == "Google") != null
            select contacts;

答案 1 :(得分:0)

我通常更喜欢混合使用一些XPath来编写这些查询,它比LINQ等价物要紧凑得多。

var query =
    from contact in doc.XPathSelectElements("/phoneBook/Contact")
    where contact.XPathSelectElements("Company/CompanyName[.='Google']").Any()
    select contact;

否则,使用LINQ:

var query =
    from contact in doc.Elements("phoneBook").Elements("Contact")
    where contact.Elements("Company").Elements("CompanyName")
        .Any(c => (string)c == "Google")
    select contact;